How to stop a thread waiting in a blocking read operation in Java? How to stop a thread waiting in a blocking read operation in Java? multithreading multithreading

How to stop a thread waiting in a blocking read operation in Java?


This is because reading System.in (InputStream) is a blocking operation.

Look here Is it possible to read from a InputStream with a timeout?


You've stumbled upon a 9 year old bug no one is willing to fix. They say there are some workarounds in this bug report. Most probably, you'll need to find some other way to set timeout (busy waiting seems unavoidable).


You could use the available() method (which is non-blocking) to check whether there is anything to read beforehand.

In pseudo-java:

//...while(running){    if(in.available() > 0)    {        n = in.read(buffer);        //do stuff with the buffer    }    else    {        Thread.sleep(500);    }}//when running set to false exit gracefully here...