intermediateConcurrency Utilities

What is the poison pill pattern, and when and how do you use it?

A poison pill is a special sentinel value placed onto a BlockingQueue specifically to tell consumer threads that it's time to stop processing and exit their loop. Once a producer has finished submitting all of the real work items, it puts one poison pill onto the queue for each consumer thread that needs to be told to stop. Each consumer, upon dequeuing the pill, recognizes it and breaks out of its processing loop instead of treating it as real work. Good practice is to use a single static final sentinel object of the same type as the real work items, and to check for it using reference identity (==) rather than equals(), to avoid accidentally matching a real item. An alternative approach uses an AtomicBoolean shutdown flag checked via a timed poll(timeout) instead of a blocking take(), which lets a consumer periodically notice the flag even without a matching pill. This pattern is a useful way to shut down a producer-consumer pipeline gracefully when interrupting the consumer threads directly is undesirable.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to How does ForkJoinPool's work-stealing algorithm work?← Back to all Java Concurrency & Multithreading questions