Java Reference
In-Depth Information
Chapter 7. Cancellation and Shutdown
It is easy to start tasks and threads. Most of the time we allow them to decide when to stop by
letting them run to completion. Sometimes, however, we want to stop tasks or threads earlier
than they would on their own, perhaps because the user cancelled an operation or the applica-
tion needs to shut down quickly.
Getting tasks and threads to stop safely, quickly, and reliably is not always easy. Java does
not provide any mechanism for safely forcing a thread to stop what it is doing. [1] Instead, it
provides interruption , a cooperative mechanism that lets one thread ask another to stop what
it is doing.
The cooperative approach is required because we rarely want a task, thread, or service to stop
immediately , since that could leave shared data structures in an inconsistent state. Instead,
tasks and services can be coded so that, when requested, they clean up any work currently in
progress and then terminate. This provides greater flexibility, since the task code itself is usu-
ally better able to assess the cleanup required than is the code requesting cancellation.
End-of-lifecycle issues can complicate the design and implementation of tasks, services, and
applications, and this important element of program design is too often ignored. Dealing well
with failure, shutdown, and cancellation is one of the characteristics that distinguishes a well-
behaved application from one that merely works. This chapter addresses mechanisms for can-
cellation and interruption, and how to code tasks and services to be responsive to cancellation
requests.
7.1. Task Cancellation
An activity is cancellable if external code can move it to completion before its normal com-
pletion. There are a number of reasons why you might want to cancel an activity:
User-requested cancellation. The user clicked on the “cancel” button in a GUI application,
or requested cancellation through a management interface such as JMX (Java Manage-
ment Extensions).
Time-limited activities. An application searches a problem space for a finite amount of
time and chooses the best solution found within that time. When the timer expires, any
tasks still searching are cancelled.
Search WWH ::




Custom Search