BlockingQueue Producer Consumer Shutdown
Coordinate producer and consumer threads through an ArrayBlockingQueue with a poison-pill sentinel so shutdown is deterministic and lossless.
Code
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class PipelineShutdown {
private static final String POISON = "<<poison>>";
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(64);
Thread producer = Thread.ofPlatform().start(() -> {
try {
for (int i = 0; i < 20; i++) {
queue.put("job-" + i);
}
queue.put(POISON);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = Thread.ofPlatform().start(() -> {
try {
while (true) {
String job = queue.take();
if (POISON.equals(job)) {
break;
}
System.out.println("processing " + job);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.join();
consumer.join();
System.out.println("pipeline drained cleanly");
}
}How it works
Count the class PipelineShutdown as the entire surface area of BlockingQueue Producer Consumer Shutdown.
The one repetition in this snippet is the loop for (int i = 0; i < 20; i++).
Using it
The demo output is labeled (processing, pipeline drained cleanly), so each line traces straight back to the statement that printed it.
Key statements
Thread producer = Thread.ofPlatform().start(() -> {
try {
for (int i = 0; i < 20; i++) {
queue.put("job-" + i);
}
queue.put(POISON);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Interactive Tools for This Topic
FAQ
- What does BlockingQueue Producer Consumer Shutdown print when run?
- The script runs standalone; its 2 labeled outputs include `processing`, `pipeline drained cleanly`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.