Video in progress
How do you build producer-consumer with a BlockingQueue?
The producer puts items in with put() and the consumer takes them with take(). If the queue is full, the producer waits automatically, and if it is empty, the consumer waits, so there is no need to write wait/notify by hand.
📖 Answer
BlockingQueue<Event> queue = new ArrayBlockingQueue<>(500);
// producer
Thread producer = Thread.ofPlatform().name("reader").start(() -> {
try {
for (Event e : readEvents()) {
queue.put(e); // waits if it is full
}
queue.put(Event.POISON); // the "no more items" signal
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
});
// consumer
Thread consumer = Thread.ofPlatform().name("writer").start(() -> {
try {
while (true) {
Event e = queue.take(); // waits if it is empty
if (e == Event.POISON) break;
save(e);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
});
The methods come in four behaviors: add/remove throw an exception, offer/poll return false/null right away, put/take block, and offer(e, timeout)/poll(timeout) wait for a limited time.
Which queue: ArrayBlockingQueue has a fixed capacity; with LinkedBlockingQueue always set the capacity (the default is Integer.MAX_VALUE); PriorityBlockingQueue orders by priority.
A "poison pill" is a simple way to stop a consumer cleanly. If there are several consumers, you have to put one in for each.
Sign up to mark studied questions and save your progress.