Java Reference
In-Depth Information
A task should not assume anything about the interruption policy of its executing thread unless
it is explicitly designed to run within a service that has a specific interruption policy. Wheth-
er a task interprets interruption as cancellation or takes some other action on interruption, it
should take care to preserve the executing thread's interruption status. If it is not simply go-
ing to propagate
InterruptedException
to its caller, it should restore the interruption
status after catching
InterruptedException
:
Thread.currentThread().interrupt();
Just as task code should not make assumptions about what interruption means to its executing
thread, cancellation code should not make assumptions about the interruption policy of ar-
bitrary threads. A thread should be interrupted only by its owner; the owner can encapsulate
knowledge of the thread's interruption policy in an appropriate cancellation mechanism such
as a shutdown method.
Because each thread has its own interruption policy, you should not interrupt a thread unless
you know what interruption means to that thread.
Critics have derided the Java interruption facility because it does not provide a preemptive
interruption capability and yet forces developers to handle
InterruptedException
.
However, the ability to postpone an interruption request enables developers to craft flexible
interruption policies that balance responsiveness and robustness as appropriate for the applic-
ation.
7.1.3. Responding to Interruption
As mentioned in
Section 5.4
,
when you call an interruptible blocking method such as
Thread.sleep
or
BlockingQueue.put
, there are two practical strategies for handling
InterruptedException
:
•
Propagate the exception (possibly after some task-specific cleanup), making your
method an interruptible blocking method, too; or
•
Restore the interruption status so that code higher up on the call stack can deal with
it.
Propagating
InterruptedException
can be as easy as adding
InterruptedEx-