Hi,
In
Java Concurrency in Practice[JCIP] , there is explanation about how to use cancellation and interruption in threads .This example is on Page 21 of Chapter7.Cancellation and Shutdown which states : Listing 7.3. Unreliable Cancellation that can Leave Producers Stuck in a Blocking Operation. Don't Do this.
Here actually they are telling in order to stop any
thread operation , just create a volatile flag which can be checked .Depending upon the status of that flag , thread execution stops.
Now there is one program for explaining same .It works fine there ,Below is the example :
In above code cancelled is the volatile flag which we can check for the cancellation check and thread execution stops if its true .
But if we do the same operation which we have done above but use BlockingQueue there is some problem.
If, however, a task that uses this approach calls a blocking 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 below program illustrates this problem. The producer thread generates primes and
places them on a blocking queue. If the producer gets ahead of the consumer, 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 cancelled 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).
Here is the code for the same ::
I am not able to understand why cancellation will not work in case of blocking Queue in second code example. Please explain !