Posted By:
Martin_Erren
Posted On:
Tuesday, September 18, 2001 08:10 AM
Using InputStream#read(...) causes a
blocking in the current thread, because
there's nothing to do as waiting for
input.
Sockets are concerned, other streams,
like reading from filesystem are
effective enough for to
be handled normally (with the blocking
read method).
InputStream#available()
is implemented for making a lookup
in the buffer
To take advantage of this, you have
to make a Thread.sleep() for
giving time to the other threads.
In the main-thread those are the other
applications in the OS.
InputStream in; //from Socket or other blocking stream
byte buf=new byte[BUFSIZE];
int r=0;
do {
if(in.available()>0) {
r = in.read(buf);
doSomethingWith(buf,r);
}
Thread.sleep(100/*ms*/);
} while(!timeOut());
Note, that available can return always
0 in some stream implementations. Then non-blocking-io is impossible.
Timeouts (here manually) can be
defined in the Socket constructor.