Java: how to catch interruptedexception on a thread when it is interrupted by another thread?
I'm developing a multithreaded application to connect to external servers - each on a different thread - and will be blocked until there is input Each of them extends the thread class For ease of explanation, we call it "connection thread"
All these connection threads are stored in a concurrent HashMap
I then allow restful web service method calls to cancel any threads (I'm using grizzly / Jersey, so every call is a thread.)
I retrieve a specific connection thread (from HashMap) and call the interrupt () method on it
So, this is a problem. How do I catch interruptedexception in the connection thread? (when the external restful command stops the connection thread, I want to do something.)
Solution
You can't Because if your thread is blocked in a read I / O operation, it cannot be interrupted This is because interrupts only set a flag to indicate that the thread has been interrupted However, if your thread has been blocked by I / O, it will not see this flag The correct method is to close the underlying socket (the thread is blocked), then catch the exception and propagate it Therefore, since your connection thread extends Thread, execute to
@Override public void interrupt(){ try{ socket.close(); } finally{ super.interrupt(); } }
This can interrupt blocked threads on I / O
Then execute in your run method:
@Override public void run(){ while(!Thread.currentThread().isInterrupted()){ //Do your work } }
So don't try to catch interruptedexception in your case You cannot interrupt a blocked thread on I / O Just check if your thread has been interrupted and facilitate the interruption by closing the flow