Lesson · Concurrent Collections
BlockingDeque: one end for the owner, one for thieves
13 min readBlockingDeque
A work queue where the thread that created the work takes it back from its own end, and an idle thread steals from the far end. LinkedBlockingDeque implements that shape with blocking at both ends, which is the structure work-stealing algorithms are built on.
The FIFO work queue that sends the hot work away
A pool of workers behind one FIFO queue has two costs that no diagram shows. Every worker contends for the same queue, and every worker takes the oldest task, which is exactly the task whose data has gone cold in the cache.
// One FIFO queue for everyone: correct, but every worker meets at the same ends. BlockingQueue<Task> work = new LinkedBlockingQueue<>(); void workLoop() { while (running) { Task t = work.take(); // the oldest task, whoever wins the lock for (Task child : t.split()) { work.put(child); // children go behind everyone else's work } } }
The order a queue gives you is a policy. FIFO everywhere means the newest work runs last, and every worker fights for the same ends.
Both ends, all four shapes
BlockingDeque extends BlockingQueue with the same four shapes at both ends. A thread can insert or remove at the first or the last element, and it can block or time out in every one of those directions.
The rest of the contract follows the Deque interface: the inherited Queue calls pick a side, and the throwing forms are available at both ends too.
| Call shape | First end | Last end |
|---|---|---|
| Insert, immediate | offerFirst(e) | offerLast(e) |
| Insert, times out | offerFirst(e, time, unit) | offerLast(e, time, unit) |
| Insert, blocks | putFirst(e) | putLast(e) |
| Remove, immediate | pollFirst() | pollLast() |
| Remove, times out | pollFirst(time, unit) | pollLast(time, unit) |
| Remove, blocks | takeFirst() | takeLast() |
- Inherited calls pick a side: add, put and offer act on the last end; remove, take and poll act on the first end.
- push and pop do not block: they are the throwing Deque forms (addFirst and removeFirst). The blocking stack-shaped pair is putFirst and takeFirst.
- One condition per direction: blocked inserts wait on notFull and blocked removes wait on notEmpty, whichever end they aimed at.
Both ends block, both ends time out. A deque is not a queue with extras; it is two gates with the same rules.
LinkedBlockingDeque · both ends
one lock, two conditions
owner: one end, both operations
- putFirst(child) → head
- takeFirst() → head
Newest in, newest out: LIFO. The task just created is the task whose data is warm, so the walk is depth-first on hot memory.
thief: the far end only
- takeLast() → tail
- pollLast(t, u) → tail
Oldest out: FIFO for whoever ran dry. Away from the owner, and the oldest work is the coarsest, so one steal buys a real chunk.
Both directions share the lock, because either operation can happen at either end. The end choice is about which work moves, not about which lock it takes.
The work-stealing shape: owner at one end, thieves at the other
Work stealing splits the roles of the two ends. The owner of the deque pushes new work and pops the newest element; a thief, a worker whose own deque ran dry, takes from the opposite end.
Why LIFO for the owner: the newest task is the one whose data was just touched, so the split path is likely to find it in cache. Taking the newest also makes the walk depth-first, so a worker descends one branch of the tree instead of hopping between distant subtrees, which keeps the working set small and the recursion narrow.
Why the far end for thieves: it separates them from the owner's hot end, and the far end holds the oldest items, which after a few splits are the coarsest. One steal then moves a substantial chunk of work, so the thief does not have to come straight back for another.
- Owner: one end for both operations. Newest in, newest out: LIFO, locality, depth-first.
- Thieves: the other end. Oldest out: FIFO for whoever has nothing, so the steal is worth the trip.
- Per worker, not per pool. The deque belongs to one worker; coordination happens only when somebody runs dry.
- Where this shape lives: ForkJoinPool runs exactly this internally, with its own deque and lock-free steal machinery. LinkedBlockingDeque gives you the same two-role shape with blocking semantics when the work does not fit ForkJoinTask.
LIFO locally, FIFO for stealing. Locality for the owner, balance for the thief, and the two roles never share an end.
LinkedBlockingDeque · per-worker deque
head · owner end
newest work on the left, oldest on the right
tail · thieves end
ready: takeFirst()
no work of its own: about to steal
One deque belongs to the owner worker: t4 is the newest task at the head, t1 the oldest at the tail. An idle thief is watching the far end.
Inside LinkedBlockingDeque: one lock, two conditions
LinkedBlockingDeque is a doubly linked chain: each node knows its predecessor and successor, and the deque keeps first and last references. Most operations are constant time at the ends; contains and remove(Object) walk the chain.
The lock layout is the interesting part. LinkedBlockingQueue splits into putLock and takeLock because puts only touch the tail and takes only touch the head. In a deque either operation can happen at either end, so the class keeps one ReentrantLock with two conditions (notEmpty and notFull). It also has no fairness constructor, and its no-argument capacity is Integer.MAX_VALUE, so it is unbounded unless you pass a bound.
| Class | Locks | Order | Blocks at both ends | Default capacity |
|---|---|---|---|---|
| ArrayBlockingQueue | one lock, two conditions | FIFO only | no | required at construction |
| LinkedBlockingQueue | putLock and takeLock | FIFO only | no | Integer.MAX_VALUE |
| LinkedBlockingDeque | one lock, two conditions | both ends | yes | Integer.MAX_VALUE |
| ConcurrentLinkedDeque | lock-free (CAS) | both ends | never blocks | unbounded |
- One lock, not two: the two-lock trick needs each operation to own an end permanently, and in a deque both ends accept both operations.
- Optional bound: new LinkedBlockingDeque<>(10_000) is the bounded form; the no-argument constructor is unbounded.
- No fair mode: ArrayBlockingQueue and SynchronousQueue accept a fairness flag, the linked deque and queue do not.
- Linear scans: contains, remove(Object) and removeFirstOccurrence walk the chain; only the ends are constant time.
A deque-shaped interface, a single lock inside. The extra structure versus LinkedBlockingQueue is the price of both ends blocking.
Where the two-role deque fits
The two-role shape is the reason to choose a BlockingDeque. If every thread uses one end, a plain queue is simpler and scales better, so the interesting uses are the ones where roles differ.
The deque also replaces a queue without changing call sites: add, put and offer map to the last end, take and poll to the first. What changes is cost. LinkedBlockingDeque serialises both directions on one lock, so for a pure FIFO hot path LinkedBlockingQueue (two locks) usually scales better.
- Per-worker work queues: copy the ForkJoin shape when the work does not fit ForkJoinTask, for example when workers must block, time out, or cooperate with a pool they do not own.
- Newest-first scan loops: a crawler or retry loop where the most recently discovered item is the warmest and most promising thing to try next.
- Cancel-latest patterns: takeFirst() drains the freshest work first during shutdown, or when a newer item supersedes older ones.
- Producer at one end, batch drainer at the other: putLast from producers and a takeFirst drainer, or the mirror image, under one blocking API.
Reach for the deque when order and role are the point. If every thread uses the same end, a queue does the same job with a better lock layout.
When both roles take from the same end
It is tempting to let thieves take from the end they can see best, or to make the whole deque LIFO. Both variations are legal, and both give up the reason for the second end.
- Stealing the newest task is the least useful steal: it is the most recently created item, so it is the smallest; the thief gets a sliver, finishes instantly, and comes straight back for another steal.
- Same end, same node: owner and thieves then mutate the head together. In a lock-per-end or lock-free implementation that is the hot spot the two-end split removes; with the deque's single lock the ends already serialise, so the loss is the quality of the steal rather than lock contention.
- Pure LIFO starves the oldest work: if arrivals keep coming and only the newest end is used, the oldest items wait forever. The thief side is also the FIFO side, and it is what drains old work.
- Steal coarse, not crumbs: a thief that takes one coarse task does far more work per trip than one that keeps taking single fine-grained items.
Two roles, two ends. The moment both roles use one end, the deque is a stack with extra steps.
The decision sequence
Answer these in order; the first three pick the shape and the last three pick the configuration.
- Is it a pipeline? Producers in, consumers out, one order: BlockingQueue, and you pay less for the same semantics.
- Do the threads have different roles? An owner and thieves, a newest-first worker and an oldest-first drainer: BlockingDeque.
- Do both ends need to block? If a thread must park waiting for work at one end or room at the other, the concurrent (non-blocking) deque is out; it never blocks.
- Do you need fairness between parked threads? Neither linked class offers it; ArrayBlockingQueue(capacity, true) does, for a FIFO shape.
- Bound it. new LinkedBlockingDeque<>(n) with a real n, or the same Integer.MAX_VALUE default the queue has.
- Feed the far end with the coarse work. If thieves should be useful, arrange that the oldest end holds the bigger chunks.
Owner LIFO, thief FIFO, bound it. Three decisions, and the deque's behaviour is fully specified.
The steal that took the smallest crumb
A thief wired to the owner's end takes the newest, smallest task: it finishes in microseconds and immediately steals again, so the overhead per unit of work climbs while the owner's cache locality drops. On a deque whose two ends are roles, the far end is the whole design. Same-end usage is not incorrect, it is just a stack with a coordination problem attached.
Interview angles
Why would the owner take the newest task while an idle worker takes the oldest?+
Roles. The owner keeps locality (the newest work was just touched, so it is warm in cache) and walks depth-first, while a thief takes the far end: away from the owner's hot end, and holding the coarsest, oldest work, so one steal buys real work.
The two choices are complementary: LIFO on one end for locality, FIFO on the other for balance and for draining old work.
How many locks does LinkedBlockingDeque use?+
One ReentrantLock with two conditions, notEmpty and notFull. LinkedBlockingQueue can split puts and takes onto separate locks because each owns one end permanently; in a deque both operations happen at either end, so the single lock is structural.
Common misconception: A deque must use two locks, one per end, to be efficient.
How does this relate to ForkJoinPool?+
ForkJoinPool implements the same shape internally with its own deque and work-stealing machinery, tuned for ForkJoinTask. LinkedBlockingDeque gives you the two-end shape with blocking and timeouts when your work does not fit that framework.
What is the cost of using a deque as a plain FIFO queue?+
The semantics are the same through the inherited calls, but the structure is heavier: one lock for both directions instead of two, plus a node per element. For a pure FIFO hot path, LinkedBlockingQueue is the better-scaled choice.
What goes wrong if only the newest end is ever used?+
The oldest items can starve under continuous arrivals, and stealing, if you add it later, takes the finest-grained tasks. The far end is the FIFO side, and it is what drains old work.
Common misconception: LIFO versus FIFO only affects performance, never which items eventually run.