Lesson · Multithreading Fundamentals
Producer-Consumer: the bounded buffer every system rebuilds
14 min readProducer-Consumer Pattern
One queue, two rates, and a rule about memory: the buffer absorbs bursts, and its capacity is what applies backpressure. The pattern is the shape of thread pools, log pipelines and almost every ingestion path you will ever wire up.
Two rates that never match
A producer generates work at its own rate and a consumer drains it at a different one. Wiring them directly couples the two: the fast side waits on the slow side, and every burst becomes a stall. A queue in the middle decouples them, absorbs the burst, and turns "block for a moment" into "hold a moment".
The queue is also where the memory policy lives. A bound of N says the system will hold at most N items; when the bound is reached, the producer must wait. That wait is not a defect, it is the feature: backpressure tells the fast side to slow down while the data is still recoverable.
Remove the bound and the failure moves rather than disappears. An unbounded queue accepts every item until the heap has none left, and an OutOfMemoryError is a much worse outcome than a producer that runs a little slower.
The buffer, drawn
A bounded buffer is the whole pattern in one picture: producers on the left, a fixed row of slots, consumers on the right, and two conditions that make the two sides take turns. Full stops producers, empty stops consumers, and nothing else coordinates them.
Hand-rolled, that is one monitor with two wait conditions, one for notFull and one for notEmpty, and every loop follows the wait-notify protocol: while the condition you need is false, wait; after changing the state, signal.
Why two conditions instead of one wait set: a signal should tell a specific side that its condition changed. On synchronized you get one wait set per monitor, so two logical conditions mean notifyAll (correct, slightly wasteful), or a ReentrantLock with two Condition objects, where signal() targets only the notEmpty consumers or only the notFull producers. The locks lesson covers that API; the protocol underneath is identical.
One monitor, two conditions. Producers wait for notFull, consumers wait for notEmpty, and every signal belongs to the condition that just changed.
Bounded buffer
capacity 4, one pill at the tail
producer threads
- put(e): blocks while full
- offer(e, t, u): gives up after t
- the fast side slows down here
bounded queue
capacity 4The capacity is the memory bound, and each annotation sits on the edge it applies to: an empty queue stops the consumer side, a full queue stops the producer side.
consumer threads
- take(): blocks while empty
- poll(t, u): gives up after t
- the pill arrives through this door
One pill per consumer, enqueued after every real item: FIFO order means the sentinel cannot overtake the work it follows.
The rewrite: BlockingQueue
java.util.concurrent already implements the pattern, so production code rarely hand-rolls it: put() blocks while the queue is full, take() blocks while it is empty, and both conditions are internal. ArrayBlockingQueue is a fixed array with one lock and two conditions; LinkedBlockingQueue is optionally bounded, and its optional bound defaults to Integer.MAX_VALUE.
Every blocking call has a non-blocking and a time-bounded sibling, and the choice between them is a policy decision rather than a style preference: block until it fits, give up immediately, or wait a bounded time and then decide.
| Operation | Throws exception | Special value | Blocks | Times out |
|---|---|---|---|---|
| insert | add(e) | offer(e) returns false | put(e) | offer(e, time, unit) |
| remove | remove() | poll() returns null | take() | poll(time, unit) |
| examine | element() | peek() returns null | not applicable | not applicable |
- drainTo(collection) moves a whole batch into a collection under one lock acquisition, which is the cheap way to hand a backlog to a database writer.
- new ArrayBlockingQueue<>(capacity, true) turns on fairness: threads blocked in put and take acquire in FIFO order, at a measurable cost in throughput.
- Null is not allowed. BlockingQueue implementations reject null elements with NullPointerException, so a sentinel shutdown value has to be a real value.
Blocking is the feature
The three full-queue policies are not stylistic. put() applies backpressure and keeps memory bounded; offer() with a timeout sheds load after a bounded wait; offer() without one drops the item immediately, which has to be a decision rather than an accident.
Unbounded queues move the failure to the heap. new LinkedBlockingQueue<>() is unbounded in practice, because its capacity is Integer.MAX_VALUE: acceptable for a short-lived pipeline, a liability for anything that can ingest faster than it drains.
A bounded queue fails slowly; an unbounded queue fails catastrophically. Put the bound where the slow failure is still acceptable, and the slow failure is what you will see first.
Shutting it down: the poison pill
Consumers block inside take(), so a shutdown boolean is not enough: a parked thread never re-checks it. The poison pill makes the signal part of the data. Enqueue a sentinel after the last real item, and each consumer exits the loop when it takes one.
One pill per consumer, enqueued last, from a single place. Give fewer pills than consumers and someone blocks forever; give more and the extras sit in the queue. With a pool, interrupting the workers is the cleaner alternative, and it forces the InterruptedException discipline you want anyway: catch it, stop, and either exit or restore the flag.
- Stop accepting new work: producers finish the items they were given and enqueue nothing more.
- Enqueue one pill per consumer, after every real item, from one coordinator rather than from each producer.
- Consumers take() until the pill arrives, then leave their loop. A consumer already blocked in take() wakes when the pill reaches it.
- join() the consumers, then report. The queue drains in order, so pills cannot overtake real work.
Bounded queue · capacity is the memory bound
queue · capacity 2
blocked on
A parked thread is waiting on a condition; a blocked one is queued for the lock.
about to put(1)
about to take()
Capacity 2, empty queue, one producer and one consumer. The queue is the only contract between them: the producer writes into it, the consumer reads from it, and neither needs to know the other rate.
accent = producer · violet = consumer · amber = parked or blocked · emerald = the pill and the finished state
Four bugs this pattern ships
Every one of these has been written by everybody at least once, and each has a cheap fix once you can name the mechanism.
- if instead of while around the wait. A wakeup is a hint to re-check, not proof of the condition. Symptom: one item silently disappears, or an index walks off the end, rarely and unpredictably.
- notify() with two conditions on one monitor. The signal lands on a waiter of the other condition, which consumes it, re-tests, and parks again, while the thread that could have progressed never wakes. Fix: notifyAll, or two Condition objects with a targeted signal().
- Swallowing InterruptedException and continuing. The catch block that logs and loops clears the interrupt flag and turns cancellation into a busy loop that ignores every later shutdown request. Stop, or restore the flag with Thread.currentThread().interrupt().
- Unbounded growth. new LinkedBlockingQueue<>() holds up to Integer.MAX_VALUE items, so a consumer that falls behind becomes memory pressure, then an OutOfMemoryError. Bound the queue and decide who slows down.
Where this pattern hides in plain sight
ThreadPoolExecutor is a producer-consumer system. execute() is the put, the worker threads are the consumers, and the work queue between them is the buffer. Its constructor asks exactly the questions this lesson asks: how large is the buffer, what happens when it is full (the rejection policy), and how many consumers work it.
Executors.newFixedThreadPool uses an unbounded LinkedBlockingQueue, which is why a pool that receives work faster than it executes grows the queue instead of rejecting anything. Choosing a bound means building the executor with an explicit queue and rejection policy rather than through the convenience factory.
Logging has the same shape. Async appenders in Log4j 2 and Logback enqueue events to a background thread on a bounded queue, and what they do when it fills is this lesson's put versus offer decision, taken on the boundary of a system that must not block.
Every task queue, log pipeline and ingestion path is a bounded buffer with a policy for full. Name the capacity and the policy, or the defaults name them for you.
The queue that ate the signal
Hand-rolled buffer, two conditions, one monitor, notify() instead of notifyAll(). An item is enqueued, the signal goes to a producer parked on notFull, and the consumer parked on notEmpty never hears about it. Nothing throws, nothing fails, and the pipeline stops until the next item happens to arrive. notifyAll is the safe default; two Condition objects with signal() are the precise one; the while loops make the extra wakeups harmless either way.
Interview angles
Why put a queue between a producer and a consumer instead of calling the consumer directly?+
To decouple the two rates. The queue absorbs bursts, bounds memory by its capacity, and applies backpressure by blocking the fast side. A direct call couples them and turns every burst into a stall.
Why is an unbounded queue dangerous?+
It replaces a scheduling problem with a resource failure: the queue keeps accepting until the heap is exhausted, and that takes the whole process down. A bound converts the same overload into a producer that runs slower, which is recoverable and visible.
How do you shut consumers down cleanly?+
Enqueue one poison pill per consumer after all real work, so each consumer takes its pill and exits. With a pool, interrupt the workers instead, and honour InterruptedException rather than swallowing it.
notify() or notifyAll() in a hand-rolled buffer?+
notifyAll, because one monitor holds two conditions and notify can hand the signal to a thread waiting for the other one. With a ReentrantLock you can be precise instead: notFull.signal() wakes a producer, notEmpty.signal() wakes a consumer.
Common misconception: notify() wakes the thread that has waited the longest.
What does BlockingQueue.put do that offer does not?+
put blocks until there is room, so it applies backpressure. offer returns false immediately if the queue is full, and the timed overload waits up to a bound. Choosing between them is choosing the overload policy: block, shed, or time out.
Where does this pattern appear in code that never says producer-consumer?+
ThreadPoolExecutor, where tasks are the items, workers are the consumers, the work queue is the buffer and the rejection policy is the full case. Async logging appenders have the same shape, as does any ingestion pipeline in front of a database.