Lesson · Concurrent Collections
BlockingQueue Implementations: pick the shape, then the backing
15 min readBlockingQueue Implementations
Every BlockingQueue call answers the same question four ways: what happens when the queue is full or empty. The method shape you call is the overload policy; the implementation you construct is the resource policy. This lesson prices both.
One interface, four shapes per operation
The producer-consumer lesson built the bounded buffer by hand and ended with put and take as the backpressure mechanism. This lesson is the catalogue behind that queue: the four shapes the interface defines for insert, remove and examine, and the five implementations that provide them.
The shape is chosen at the call site, and it is a policy decision rather than a style preference. Throw means a full queue is a bug in your logic. Return a special value means the caller can react. Block means waiting is the desired behaviour. Time out means wait a bounded while and then decide.
| Shape | Insert | Remove | Examine | Use it when |
|---|---|---|---|---|
| Throws | add(e) | remove() | element() | a full or empty queue is a bug and you want it loud |
| Special value | offer(e) returns false | poll() returns null | peek() returns null | the caller can react: shed, log, retry later |
| Blocks | put(e) | take() | not defined | the wait is the policy: backpressure, not loss |
| Times out | offer(e, time, unit) | poll(time, unit) | not defined | wait a bounded time, then decide |
- The blocking shapes are interruptible: put, take and both timed forms declare InterruptedException, so a parked thread can be cancelled.
- Null is rejected everywhere: every implementation throws NullPointerException on a null element, which is why a shutdown sentinel must be a real value.
- remainingCapacity() is a hint, not a reservation: another thread can take the slot between your check and your offer.
The shape is the policy. put blocks, offer sheds, the timed form negotiates; the queue does not choose for you, the call site does.
BlockingQueue · gates
capacity 4, one lock, two conditions
producer threads
- put(e): blocks while full
- offer(e, t, u): gives up after t
bounded ring buffer
capacity 4put signals notEmpty on the way out, take signals notFull: each gate opens from the opposite side, and a woken thread re-checks in a while loop.
consumer threads
- take(): blocks while empty
- poll(t, u): gives up after t
Throws
- add(e)
- remove()
- element()
a full queue is a bug: fail loud
Special value
- offer(e) → false
- poll() → null
- peek() → null
the caller reacts there and then
Blocks
- put(e)
- take()
the wait is the policy: backpressure
Times out
- offer(e, t, u)
- poll(t, u)
bounded wait, then decide
Inside the gates: how put actually waits
Blocking is not polling. put acquires the queue lock, checks the count, and if the queue is full it parks on a Condition: a wait queue attached to the lock. A parked producer burns no CPU, and only a signal from the other side can wake it.
The signal comes from the opposite operation. A take that removes an element signals notFull before returning; a put that inserts signals notEmpty. The woken thread still has to reacquire the lock and re-check the condition, which is why the check in the source is a while loop, not an if.
- One lock, two conditions in ArrayBlockingQueue: notFull holds the parked producers, notEmpty holds the parked consumers.
- Each side wakes the other: put signals notEmpty, take signals notFull; spare wakeups are harmless because the loop re-checks.
- Fairness is a constructor flag on ArrayBlockingQueue: blocked threads then acquire in FIFO order, at a measurable throughput cost.
- Interruption ends a wait: Shutdown no longer needs to enqueue anything; interrupting the workers makes both blocked calls throw InterruptedException.
The block is the backpressure. Nothing is dropped and nothing is retried: the producer simply waits until there is room, and the queue size is the amount of work the system holds.
ArrayBlockingQueue · one lock, two conditions
bounded queue · capacity 3
empty: notEmpty parks consumersready: put(1)
ready: put(2)
ready: take()
A capacity-3 ArrayBlockingQueue with two producers and one consumer. One lock guards both ends, and two conditions split the waiters: notFull parks producers, notEmpty parks consumers.
ArrayBlockingQueue: the fixed ring
ArrayBlockingQueue is a fixed array with two indices walking around it: put writes at the tail index, take reads at the head index, and both wrap. The array is allocated in the constructor, so capacity keeps a million slots of references alive from the moment the queue exists, whether it is empty or full.
One ReentrantLock guards both ends and the count, with the two conditions splitting the waiters by what they are waiting for. Pick it when the ceiling is a design constant you want impossible to forget.
- Bounded by construction: there is no unbounded constructor; capacity is the first argument, and it is required.
- One lock: producers and consumers do not overlap inside the queue, which is why the linked version can beat it under heavy contention.
- Pre-allocated memory: the cost is capacity times a reference, paid up front rather than per element.
- A ring, not a shifting list: head and tail indices advance and wrap, so no element ever moves.
Predictable beats clever. A fixed array with a known ceiling is the easiest bounded queue to reason about in production.
LinkedBlockingQueue: two locks, and a quiet default
LinkedBlockingQueue is a chain of nodes with the work split in two: putLock (with notFull) guards the tail, takeLock (with notEmpty) guards the head, and an AtomicInteger count is shared between them. Producers and consumers proceed at the same time, which is why it often wins on throughput for plain FIFO work.
The default constructor is the part that matters. With no argument, capacity is Integer.MAX_VALUE, so the queue is unbounded in practice; it is only a bounded queue when you pass a bound. Same class, opposite policy, one constructor argument.
- Two locks, one count: each operation touches one lock, and the atomic count lets both sides read progress without the other lock.
- Node per element: allocation on every put, plus pointer overhead, which shows up as GC work on a hot queue.
- drainTo is the batch path: it moves elements in one pass under the take lock instead of one lock acquisition per poll.
- Bound it on purpose: new LinkedBlockingQueue<>(10_000) is the bounded form, and it is the one you want in an ingest path.
The default capacity is the trap. One constructor argument is the difference between a bounded pipeline and unbounded memory growth.
The specialists: priority, handoff, delay, transfer
Four more implementations exist because FIFO-by-capacity is not the only policy an ingest path needs. Each changes what full means.
| Implementation | Capacity | At the gates | Reach for it when |
|---|---|---|---|
| ArrayBlockingQueue | fixed, required | one lock; put and take block | the ceiling is known and must be enforced |
| LinkedBlockingQueue | optional; unbounded by default | two locks; put and take block | FIFO with a bound you set on purpose |
| PriorityBlockingQueue | unbounded | put never blocks; take returns the least | order matters more than arrival |
| SynchronousQueue | zero | put waits for a taker; offer fails unless one waits | direct handoff, no storage at all |
| DelayQueue | unbounded | take returns the earliest expired element | retries, timeouts, scheduled work |
| LinkedTransferQueue | unbounded | transfer(e) waits for the consumer | a handoff shaped like a queue |
- PriorityBlockingQueue: a binary heap under a lock, where only the take side ever parks. It is unbounded, so put never blocks (there is no full state to wait for) and take returns the least element. Use it when order matters more than arrival.
- SynchronousQueue: zero capacity, a pure handoff. A put waits for a take, and offer fails immediately unless a consumer is already waiting. Executors.newCachedThreadPool uses it, and that is exactly the mechanism that grows the pool: a task that nobody picks up instantly forces a new thread.
- DelayQueue: unbounded, and holds elements that implement Delayed. take blocks until the earliest element's delay has expired, which makes it the structure behind retries, timeouts and scheduled work.
- LinkedTransferQueue: adds transfer(e), which waits until a consumer receives the element itself. Ordinary puts still store when nobody is waiting; a transfer exists for the case where the handoff is the point.
Capacity is a policy. These backings differ mostly in what full means: impossible, instant, or a wait, and that is what you are really choosing.
Bounded versus unbounded: where the failure goes
A bounded queue turns overload into waiting. The producer that pulled ahead slows to the consumer's rate while the data is still recoverable, and the queue size is the amount of work the system is willing to hold. An unbounded queue converts the same overload into memory: every put succeeds until the heap has no room left, and OutOfMemoryError is not a policy you can recover from.
Two smaller rules complete the picture. drainTo moves batches, which is the right shape for a database writer behind a queue, and null is rejected everywhere, so a sentinel shutdown value has to be a real value.
queue.put(item); // block until there is room: backpressure if (!queue.offer(item)) drop(item); // shed now, visibly if (!queue.offer(item, 200, TimeUnit.MILLISECONDS)) defer(item); // bounded wait, then decide
- Backpressure: put holds the producer at the boundary, nothing is dropped, and the memory bound is exact.
- Load shedding: offer returns false (or decides after the timeout) and your code discards the item where you can see it.
- The failure mode moves: unbounded defers the failure to the heap, where it is fatal instead of slow.
- Batch transfer: drainTo(c) and drainTo(c, max) hand over many elements in one pass, ready for one batched write.
An unbounded queue is a memory leak with extra steps. The puts still succeed; only the failure is different, and it arrives later, at the heap.
The decision sequence
Answer these in order. The first two settle the policy; the rest pick the backing.
- Decide who absorbs the overload. Blocking producers means put; shedding or deferring means offer, with or without a timeout. The queue records the decision.
- State a capacity. If you cannot name one, name the reason it does not exist, because the default is how the heap ends up holding the backlog.
- Pick the order. FIFO is Array or Linked. Priority replaces arrival with comparison. Delay replaces it with time. SynchronousQueue replaces storage with a handoff.
- Pick the memory profile. A pre-allocated fixed array versus a node allocation per element; both are bounded or not, but the cost appears in different places.
- Decide on fairness, if it matters. ArrayBlockingQueue(capacity, true) makes blocked threads take turns in FIFO order, and it costs throughput.
- Check the batch path. A database writer behind the queue wants drainTo and batched writes, not a poll loop with one round trip per element.
Shape, then backing. put versus offer is a policy decision; Array versus Linked is a resource decision. Most incidents come from leaving both to a default.
The queue you never bounded
The default constructors are the trap. new LinkedBlockingQueue<>() has a capacity of Integer.MAX_VALUE, and PriorityBlockingQueue has no full state at all, so put returns immediately forever. Both feel convenient (the queue never blocks), and both mean the producer is now unbounded: the backlog grows until the heap ends, and OutOfMemoryError arrives in place of a stall. If the fast side must be limited, a bound plus put is the mechanism; write the capacity down where the queue is created, or that decision was made by a default.
Interview angles
Why does BlockingQueue define every operation four times?+
Because full and empty are policy decisions: throw, return a special value, block, or block up to a timeout. The shape you call selects the policy at that call site.
The timeouts exist so a service can wait without waiting forever: retry, log, shed, or fail with a bounded delay instead of an unbounded park.
Why is new LinkedBlockingQueue<>() dangerous?+
It has no capacity argument, so capacity is Integer.MAX_VALUE: put never blocks and the queue becomes the pile where a rate mismatch accumulates until the heap runs out.
The class is not inherently unbounded; new LinkedBlockingQueue<>(10_000) is a proper backpressure queue. One constructor argument flips the policy.
Common misconception: An unbounded queue is safe because it never blocks a producer.
When is SynchronousQueue the right choice?+
When you want a handoff rather than storage: every put must meet a take, and offer fails immediately if no consumer is waiting. newCachedThreadPool uses it, and that failure is the signal that grows the pool.
With zero capacity there is no backlog to hide behind, so the submitter learns at once (or waits) that nothing picked the work up.
What is different about PriorityBlockingQueue's put?+
It cannot block. The queue is unbounded, so there is no full state; put inserts into the heap and take returns the least element. If you were relying on put to apply backpressure, that queue silently removed it.
Follow-up: What would you do instead? Bound the work upstream, or pair a bounded queue with a separate priority index.
What does drainTo buy over a loop of poll()?+
One pass under the take lock instead of one lock acquisition per element, plus a coherent batch in arrival order that is ready for a single bulk write.
The batch boundary is also the transaction boundary in most systems: drain 500 items, write 500 rows, repeat. A poll loop makes the batch boundary depend on timing.
How does fairness change ArrayBlockingQueue?+
With fair = true, blocked producers and consumers acquire the lock in FIFO order, so a producer cannot starve behind a stream of consumers. Throughput drops, because the queue now pays for ordering.
Fairness is a constructor decision because it configures the lock itself; there is no per-call switch.