Java Reference
In-Depth Information
Listing 7.4. Interruption Methods in Thread .
If a thread is interrupted when it is not blocked, its interrupted status is set, and it is up to
the activity being cancelled to poll the interrupted status to detect interruption. In this way
interruption is “sticky”—if it doesn't trigger an InterruptedException , evidence of
interruption persists until someone deliberately clears the interrupted status.
Calling interrupt does not necessarily stop the target thread from doing what it is doing;
it merely delivers the message that interruption has been requested.
A good way to think about interruption is that it does not actually interrupt a running thread;
it just requests that the thread interrupt itself at the next convenient opportunity. (These op-
portunities are called cancellationpoints .) Some methods, such as wait , sleep , and join ,
take such requests seriously, throwing an exception when they receive an interrupt request or
encounter an already set interrupt status upon entry. Well behaved methods may totally ig-
nore such requests so long as they leave the interruption request in place so that calling code
can do something with it. Poorly behaved methods swallow the interrupt request, thus deny-
ing code further up the call stack the opportunity to act on it.
The static interrupted method should be used with caution, because it clears the current
thread's interrupted status. If you call interrupted and it returns true , unless you are
planning to swallow the interruption, you should do something with it—either throw In-
terruptedException or restore the interrupted status by calling interrupt again, as
in Listing 5.10 on page 94 .
BrokenPrimeProducer illustrates how custom cancellation mechanisms do not always
interact well with blocking library methods. If you code your tasks to be responsive to inter-
ruption, you can use interruption as your cancellation mechanism and take advantage of the
interruption support provided by many library classes.
Search WWH ::




Custom Search