Alex Rivera | Logout

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

Asked 2010-11-15T08:05:03.713
22

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.

Edit
Report

2 Answers

8

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

answered 2010-11-15T09:10:39.787
2

Is it safe to close in stream in other thread? It works for me. In this case, in.read(...) throws exception SocketException.

answered 2012-03-02T05:21:45.423

Your Answer