<<< Thread interruption | Index | Thread interruption - manual checks >>> |
The InterruptedException is thrown when another thread interrupts the thread calling the blocking method
Aa s general rule of thumb, an InterruptedException should cause the overall task of the thread to be cancelled
It's generally best to set the thread's interrupted status again:
public class MyRunnable implements Runnable() {
public void run() {
try {
doSomeWork();
} catch ( InterruptedException iex ) {
}
}
private void doSomeWork()
{
try {
// do the work
} catch ( InterruptedException iex ) {
// We've been already interrupted here, but let
// the caller deal with it. To r re-throw the exception, we call
Thread.currentThread().interrupt();
// which sets the interrupt flag and re-throws the InterruptedException
}
}
}//class MyRunnable
Calling
Thread.currentThread().interrupt();
sets the interrupt flag of the current thread and will reraise the InterruptedException on it again. The caller of doSomeWork() the also gets a chance to examine the InterruptedException.
Thus,
Thread.currentThread().interrupt();
is a better alternative to simply re-throwing the InterruptedException, because it preserves the interrupted state of the current thread.
<<< Thread interruption | Index | Thread interruption - manual checks >>> |