Java Reference
In-Depth Information
Listing 7.6. Propagating
InterruptedException
to Callers.
If you don't want to or cannot propagate
InterruptedException
(perhaps because your
task is defined by a
Runnable
), you need to find another way to preserve the interruption
request. The standard way to do this is to restore the interrupted status by calling
inter-
rupt
again. What you should
not
do is swallow the
InterruptedException
by catch-
ing it and doing nothing in the
catch
block, unless your code is actually implementing the
interruption policy for a thread.
PrimeProducer
swallows the interrupt, but does so with
the knowledge that the thread is about to terminate and that therefore there is no code higher
up on the call stack that needs to know about the interruption. Most code does not know what
thread it will run in and so should preserve the interrupted status.
Only code that implements a thread's interruption policy may swallow an interruption re-
quest. General-purpose task and library code should never swallow interruption requests.
Activities that do not support cancellation but still call interruptible blocking methods will
have to call them in a loop, retrying when interruption is detected. In this case, they should
save the interruption status locally and restore it just before returning, as shown in
Listing
rupted status too early could result in an infinite loop, because most interruptible blocking
methods check the interrupted status on entry and throw
InterruptedException
im-
mediately if it is set. (Interruptible methods usually poll for interruption before blocking or
doing any significant work, so as to be as responsive to interruption as possible.)
If your code does not call interruptible blocking methods, it can still be made responsive to in-
terruption by polling the current thread's interrupted status throughout the task code. Choos-
ing a polling frequency is a tradeoff between efficiency and responsiveness. If you have high
responsiveness requirements, you cannot call potentially long-running methods that are not
themselves responsive to interruption, potentially restricting your options for calling library
code.