Java Reference
In-Depth Information
Listing 7.2. Generating a Second's Worth of Prime Numbers.
PrimeGenerator
uses a simple cancellation policy: client code requests cancellation by
calling
cancel
,
PrimeGenerator
checks for cancellation once per prime found and
exits when it detects cancellation has been requested.
7.1.1. Interruption
The cancellation mechanism in
PrimeGenerator
will eventually cause the primeseeking
task to exit, but it might take a while. If, however, a task that uses this approach calls a block-
ing method such as
BlockingQueue.put
, we could have a more serious problem—the
task might never check the cancellation flag and therefore might never terminate.
BrokenPrimeProducer
in
Listing 7.3
illustrates this problem. The producer thread gen-
erates primes and places them on a blocking queue. If the producer gets ahead of the con-
sumer, the queue will fill up and
put
will block. What happens if the consumer tries to cancel
the producer task while it is blocked in
put
? It can call
cancel
which will set the
can-
celled
flag—but the producer will never check the flag because it will never emerge from
the blocking
put
(because the consumer has stopped retrieving primes from the queue).
terruption is a cooperative mechanism for a thread to signal another thread that it should, at
its convenience and if it feels like it, stop what it is doing and do something else.