Part 3 of 6 · 1 min read
Stopping cleanly
A poison pill or an interrupt.
A consumer that loops on take() waits forever when the producers stop. It needs a way to know that no more work will come.
JCIP describes the poison pill: a recognisable object that means "stop when you get this". The queue is first-in first-out, so every job put before the pill is processed before the consumer sees it. Producers must not add work after the pill. In the example, STOP is a sentinel string compared by identity, and the consumer breaks out of its loop on seeing it. With several consumers, put one pill per consumer.
The second tool is the interrupt. Calling consumer.interrupt() makes a blocked take() throw InterruptedException. The code above catches it and restores the flag with Thread.currentThread().interrupt(). Swallowing the exception and carrying on is a common bug, since the request to stop is lost.
Use a pill when the consumer should finish queued work first. Use an interrupt when it should stop at once. Either way, wait for the consumer with join() so that nothing is cut off midway.
Check yourself:
1. Why are jobs before the pill still processed?
2. What should the catch block do with an InterruptedException?
3. How many pills do three consumers need?