Interrupting Thread in Java for hanged process

1.4k views Asked by At

If i have a thread something like this:

Thread t = new Thread(myThread);
t.start();

private static Runnable myThread = new Runnable() {
    public void run() {
        try{
            String line=null;
            while ((line = eStream.readLine()) != null){
                //do something
            }
         }
         catch (Exception e){}
    }
};  

Now what happens in while loop, at times the readLine() is hanged because it is expecting input from external process. So in that case what i am trying to do is to setup a timer and if it expires, i interrupt this thread t with t.interrupt();

Now when i try to catch InterruptedException after the try block, i am getting compile time error. Can someone tell me in this scenario, how can i catch Interrupted Exception?

Thank you

2

There are 2 answers

5
Peter Lawrey On BEST ANSWER

interrupt won't free a blocking readLine() call. You have to close the stream to do that.

You are catching the InterruptedException already (and ignoring it) with this line

catch (Exception e){}

This won't work

line = eStream.readLine().toString()

As it will throw a NullPointerException when you reach the end of file. Remove the .toString()

1
Brian Agnew On

From the doc for InterruptedException:

Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

I suspect what you're interested in is InterruptedIOException:

Signals that an I/O operation has been interrupted. An InterruptedIOException is thrown to indicate that an input or output transfer has been terminated because the thread performing it was interrupted.

I would check out this JavaSpecialists newsletter on cleanly shuttin gdown threads and particularly the subsection What about threads blocked on IO? which covers this area in some detail.