Friday, May 16, 2008

How does a thread support its own interruption in Java?


If the thread is frequently invoking methods which throw InterruptedException then the thread doesn't need to do anything extra instead it simply waits for such an exception to be caught and then it exits from its 'run' method. Example of such a method is Thread.sleep(). Such methods are designed to cancel their current operation and return immediately once they receive an interrupt.

....
try{
Thread.sleep(10000);
} catch(InterruptedException ie){
//... handling by returning from the run method
return;
}
....

On the other hand if the thread is not invoking any such method frequently then it should periodically invoke the method Thread.interrupted() to check if an interrupt has been raised or not. If yes, then it should either return or throw an InterruptedException.

....
if(Thread.interrupted()){
//... handling by throwing InterruptedException
throw new InterruptedException();
}
....



Share/Save/Bookmark


No comments: