I’m currently working on a Java concurrency refcard for DZone that will be out in a month or so. In the process of editing the chunk below landed on the cutting room floor but I thought it was a good candidate to rescue as a blog. I would be very interested in comments on it.
Java threads cannot be safely interrupted preemptively. Instead, Java applications can call Thread.interrupt() on another thread. If the other thread is in a blocking call like wait, join, or sleep, an InterruptedException is thrown. Otherwise, the thread’s interrupted flag is set.
A thread receiving an InterruptedException has several options:
- Handle the interrupt by performing some action. A common action is to check whether some condition is true (the thread should be stopped or change modes) and alter the behavior of the thread before going back to work.
- Propagate the exception. Rethrow the InterruptedException to let higher-level code decide how to handle the interrupt.
- Defer handling of the interrupt. This is done by calling Thread.currentThread().interrupt() to reset the interrupted flag on this thread. Higher level code can then check and deal with the interruption state as needed.
- Ignore the exception. Catch and swallow the interruption. This should be avoided unless the code catching the InterruptedException is actually the code that knows the interruption policy for this thread. In that case, this is simply a special case of “handle the interrupt”.
Think carefully about the interruption policy for each thread and how code with blocking methods should respond in the context of an interrupt. Most commonly, frameworks and libraries should propagate the exception, letting the application handle the exception according to the thread’s interrupt policy.