Handle InterruptedException
In thread-related code, you will often need to handle an InterruptedException. There are two common ways of handling it :
- just throw the exception up to the caller (perhaps after doing some clean up)
- call the interrupt method on the current thread
In the second case, the standard style is :
try {
...thread-related code...
}
catch(InterruptedException ex){
...perhaps some error handling here...
//re-interrupt the current thread
Thread.currentThread().interrupt();
}
Background
In multi-threaded code, threads can often block; the thread pauses execution until some external condition is met, such as :- a lock is released
- another thread completes an operation
- some I/O operation completes
- and so on...
Threads can be interrupted. An interrupt asks a thread to stop what it's doing in an orderly fashion. However, the exact response to the interrupt depends on the thread's state, and how the thread is implemented :
if the thread is currently blocking
stop blocking early
throw InterruptedException
else thread is doing real work
thread's interrupted status is set to true
if thread polls isInterrupted() periodically
(which is preferred)
orderly cleanup and stop execution
throw InterruptedException
else
regular execution continues
The main idea here is that an interrupt should not shutdown a thread immediately, in the middle of a computation.
Rather, a thread and it's caller communicate with each other to allow for an orderly shutdown.
See also this article by Brian Goetz.
Would you use this technique?
|
|