Java Reference
In-Depth Information
7.1.2. Interruption Policies
Just as tasks should have a cancellation policy, threads should have an interruptionpolicy . An
interruption policy determines how a thread interprets an interruption request—what it does
(if anything) when one is detected, what units of work are considered atomic with respect to
interruption, and how quickly it reacts to interruption.
The most sensible interruption policy is some form of thread-level or servicelevel cancella-
tion: exit as quickly as practical, cleaning up if necessary, and possibly notifying some own-
ing entity that the thread is exiting. It is possible to establish other interruption policies, such
as pausing or resuming a service, but threads or thread pools with nonstandard interruption
policies may need to be restricted to tasks that have been written with an awareness of the
policy.
It is important to distinguish between how tasks and threads should react to interruption.
A single interrupt request may havemore than one desired recipient—interrupting a worker
thread in a thread pool can mean both “cancel the current task” and “shut down the worker
thread”.
Tasks do not execute in threads they own; they borrow threads owned by a service such as
a thread pool. Code that doesn't own the thread (for a thread pool, any code outside of the
thread pool implementation) should be careful to preserve the interrupted status so that the
owning code can eventually act on it, even if the “guest” code acts on the interruption as well.
(If you are house-sitting for someone, you don't throw out the mail that comes while they're
away—you save it and let them deal with it when they get back, even if you do read their
magazines.)
This is why most blocking library methods simply throw InterruptedException in re-
sponse to an interrupt. They will never execute in a thread they own, so they implement the
most reasonable cancellation policy for task or library code: get out of the way as quickly as
possible and communicate the interruption back to the caller so that code higher up on the
call stack can take further action.
A task needn't necessarily drop everything when it detects an interruption request—it can
choose to postpone it until a more opportune time by remembering that it was interrupted, fin-
ishing the task it was performing, and then throwing InterruptedException or other-
wise indicating interruption. This technique can protect data structures from corruption when
an activity is interrupted in the middle of an update.
Search WWH ::




Custom Search