Java Reference
In-Depth Information
Application events. An application searches a problem space by decomposing it so that
different tasks search different regions of the problem space. When one task finds a
solution, all other tasks still searching are cancelled.
Errors. A web crawler searches for relevant pages, storing pages or summary data to disk.
When a crawler task encounters an error (for example, the disk is full), other crawling
tasks are cancelled, possibly recording their current state so that they can be restarted
later.
Shutdown. When an application or service is shut down, something must be done about
work that is currently being processed or queued for processing. In a graceful shut-
down, tasks currently in progress might be allowed to complete; in a more immediate
shutdown, currently executing tasks might be cancelled.
There is no safe way to preemptively stop a thread in Java, and therefore no safe way to pree-
mptively stop a task. There are only cooperative mechanisms, by which the task and the code
requesting cancellation follow an agreed-upon protocol.
One such cooperative mechanism is setting a “cancellation requested” flag that the task
checks periodically; if it finds the flag set, the task terminates early. PrimeGenerator
in Listing 7.1 , which enumerates prime numbers until it is cancelled, illustrates this tech-
nique. The cancel method sets the cancelled flag, and the main loop polls this flag be-
fore searching for the next prime number. (For this to work reliably, cancelled must be
volatile .)
Listing 7.2 shows a sample use of this class that lets the prime generator run for one second
before cancelling it. The generator won't necessarily stop after exactly one second, since there
may be some delay between the time that cancellation is requested and the time that the run
loop next checks for cancellation. The cancel method is called from a finally block
to ensure that the prime generator is cancelled even if the the call to sleep is interrupted.
If cancel were not called, the prime-seeking thread would run forever, consuming CPU
cycles and preventing the JVM from exiting.
A task that wants to be cancellable must have a cancellation policy that specifies the “how”,
“when”, and “what” of cancellation—how other code can request cancellation, when the task
checks whether cancellation has been requested, and what actions the task takes in response
to a cancellation request.
Consider the real-world example of stopping payment on a check. Banks have rules about
how to submit a stop-payment request, what responsiveness guarantees it makes in process-
Search WWH ::




Custom Search