Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a thread that executes the following code:

public void run() {
    try {
        int n = 0;
        byte[] buffer = new byte[4096];
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
            out.flush();
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

where in is System.in. How can I stop such thread gracefully? Neither closing System.in, nor using Thread.interrupt appear to work.

like image 771
vitaut Avatar asked Nov 15 '10 08:11

vitaut


3 Answers

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

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

like image 56
PeterMmm Avatar answered Sep 23 '22 19:09

PeterMmm


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).

like image 32
Denis Tulskiy Avatar answered Sep 22 '22 19:09

Denis Tulskiy


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...
like image 29
Paolo Avatar answered Sep 25 '22 19:09

Paolo