Poison Pill Queue Shutdown
End a consumer loop by sending a sentinel object through the queue: the producer appends it after the last job and the consumer breaks on identity.
Code
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class PoisonPillShutdown {
record Job(int id, String payload) {}
// dedicated sentinel object: seeing it in the queue means there is no more work
private static final Job POISON_PILL = new Job(-1, "shutdown");
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Job> queue = new LinkedBlockingQueue<>();
Thread consumer = new Thread(() -> {
try {
while (true) {
Job job = queue.take();
if (job == POISON_PILL) {
// compare the sentinel with == so a real task with equal content is never mistaken for it
System.out.println("consumer: pill seen, exiting loop");
break;
}
System.out.println("consumer: processed job " + job.id());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
consumer.start();
queue.put(new Job(1, "resize-image"));
queue.put(new Job(2, "send-email"));
queue.put(POISON_PILL); // poison the queue when the producer finishes: the consumer exits on its own
consumer.join();
System.out.println("main: consumer finished cleanly");
}
}How it works
Poison Pill Queue Shutdown reduces to the classes PoisonPillShutdown and Job.
Repetition is confined to while (true) — the rest of the file is straight-line.
Using it
Output lines are prefixed (consumer: pill seen, exiting loop, consumer: processed job, main: consumer finished cleanly), making each step’s effect easy to spot.
Key statements
Thread.currentThread().interrupt();
Interactive Tools for This Topic
FAQ
- What does Poison Pill Queue Shutdown print when run?
- The script runs standalone; its 3 labeled outputs include `consumer: pill seen, exiting loop`, `consumer: processed job`, `main: consumer finished cleanly`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.