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.

} catch(InterruptedException ie){
//... handling by returning from the run method

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.

//... handling by throwing InterruptedException
throw new InterruptedException();


No comments: