Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How do I catch InterruptedException on a thread, when interrupted by another thread?

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

like image 218
ikevin8me Avatar asked Sep 01 '12 19:09

ikevin8me


1 Answers

So, here is the question, within the connection thread, how do I catch the InterruptedException?

You can not. Since if your thread is blocked on a read I/O operation it can not be interrupted. This is because the interrupt just 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 Thread do the following:

@Override  
public void interrupt(){  
   try{  
      socket.close();  
   }  
   finally{  
     super.interrupt();  
   }  
}   

This way it is possible to interrupt a thread blocked on the I/O.

Then in your run method do:

@Override  
public void run(){  

    while(!Thread.currentThread().isInterrupted()){    
       //Do your work

    }  
}    

So in your case don't try to catch an InterruptedException. 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.

like image 76
Cratylus Avatar answered Nov 09 '22 17:11

Cratylus