Producer-Consumer with Bounded Queue
TechniqueConcurrencyMidSeniorUpdated
Producers offer work to a fixed-capacity queue; consumers drain it. Bound provides natural backpressure when consumers fall behind.
When to Use Producer-Consumer with Bounded Queue
Decoupling fast producers from slower consumers (log shipping, request handoff, batch ingestion). Unbounded queues are an anti-pattern, they hide backpressure until OOM.
In Practice
Java's
ArrayBlockingQueue and LinkedBlockingQueue (used inside ThreadPoolExecutor). Disruptor's ring buffer at LMAX. Kafka producer's in-memory RecordAccumulator queue.Sketch
Java
BlockingQueue<Event> q = new ArrayBlockingQueue<>(10_000);
// producer
boolean accepted = q.offer(event, 50, TimeUnit.MILLISECONDS);
if (!accepted) metrics.dropped.inc();
// consumer
while (true) {
Event e = q.take();
process(e);
}How Producer-Consumer with Bounded Queue Comes Up in Interviews
Scenario
A log shipper's producer thread pushes 200k events/sec into an in-memory queue read by a network thread doing TLS. Memory keeps creeping up until OOM. The queue is unbounded. What's the standard fix?
Replace the unbounded queue with a bounded blocking queue; producers block (or drop) when the queue is full, which is backpressure. The unboundedness is the bug, it hides slow consumers until the heap dies.
Pair the bounded queue with an explicit offer(event, timeout) and a dropped-message metric. Silent block forever is worse than a visible drop: you want the symptom to surface in a dashboard, not a memory dump.