I’m developing a multithreaded application to make connections to external servers – each on separate threads – and will be blocked until there is input. Each of these extends the Thread class. For the sake of explanation, let’s call these “connection threads”.
All these connection threads are stored in a concurrent hashmap.
Then, I allow RESTful web services method call to cancel any of the threads. (I’m using Grizzly/Jersey, so each call is a thread on its own.)
I retrieve the specific connection thread (from the hashmap) and call the interrupt() method on it.
So, here is the question, within the connection thread, how do I catch the InterruptedException? (I’d like to do something when the connection thread is stopped by an external RESTful command.)
You can not. Since if your thread is blocked on a read I/O operation it can not be
interrupted. This is because theinterruptjust sets a flag to indicate that the thread has been interrupted. But if your thread has been blocked for I/O it will not see the flag.The proper way for this is to close the underlying socket (that the thread is blocked to), then catch the exception and propagate it up.
So since your connection threads
extend Threaddo the following:This way it is possible to interrupt a thread blocked on the I/O.
Then in your
runmethod do:So in your case don’t try to
catchanInterruptedException. You can not interrupt the thread blocked on I/O. Just check if your thread has been interrupted and facilitate the interruption by closing the stream.