Link to home
Start Free TrialLog in
Avatar of glow060197
glow060197

asked on

unblocking a read on System.in

how can i unblock a read on System.in and other InputStreams, from a different thread or whatever?

thanks
ASKER CERTIFIED SOLUTION
Avatar of Sendoh
Sendoh
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of stimpyjcat
stimpyjcat

As Sendoh suggests, closing a stream will cause any pending reads to return.

Alternatively, you can change the read loops to only invoke read when there are bytes pending to be read, i.e. available returns non-zero.

boolean done = false;
while (!done) {
     if (in.available()) in.read()
     // sleep or wait
}


Then another thread can simply set done = true in order to stop the reading thread.
Just want to point out that there may be a synchronization problem. When 2 threads are working on the same stream object, one read may lock the object and disallow the other to close it.
Neither the "read" nor the "close" methods on a stream are synchronized.