Lesson · Concurrent Collections
ConcurrentLinkedDeque: both ends, still lock-free
15 min readConcurrentLinkedDeque
A deque where both ends accept and release without a lock. Adding at an end is one CAS, the same shape as the lock-free queue; deleting a node is the harder half, because a doubly linked node is referenced from two sides at once. The result is lock-free access at both ends, with the same missing counter and the same weakly consistent iterators.
A deque that parks nobody
A deque is two queues sharing one structure: push at the front and it behaves as a stack, add at the back and it behaves as a queue, and doing both at once is how work gets distributed between threads. LinkedBlockingDeque covers that with a lock, and for most systems it is the right tool. ConcurrentLinkedDeque covers the residue: both ends, no blocking calls at all, no thread ever parked.
The price is not hidden. The JDK's own notes estimate this class at roughly 40 percent overhead relative to ConcurrentLinkedQueue, because a second end means a second link per node and because deleting from the middle of a doubly linked list is a genuinely harder problem. Reach for it when the requirement is real, not because lock-free sounds impressive.
Everything you learned about the lock-free queue carries over: CAS loops instead of locks, offer and poll instead of put and take, no nulls, no capacity, no counter behind size(). What is new is the middle of the list, where a removal has two neighbours to talk to.
A lock-free deque buys non-blocking access at both ends and pays for it everywhere else.
The ends are one CAS each. The middle is the work.
Adding at an end is the easy half, and the shape is the same at both ends. The node that sits at the end holds an outward link that is null precisely while it is the end, so linking the new node is a CAS on that single field. At the front, the old first node has prev equal to null; the CAS changes it to the new node, and the new node is live at that instant. The head pointer is then swung or skipped as a hint, exactly like tail in the queue.
Interior insertion is not supported, and that is not an omission. The Deque interface never asks to insert in the middle, so the implementation only has to support interior removal. That single constraint is what keeps the class tractable.
Removal from the middle is where a doubly linked list stops being symmetric. A node in the interior is referenced from two sides at once, so making it disappear involves both of its neighbours, and either neighbour may already be dead itself while still linked into the chain.
Ends speak one CAS. The middle speaks two, and it has to agree with both neighbours.
Deleting a node: mark it, then unlink it twice
Deletion happens in stages, and the stages have very different jobs. Stage one is the logical deletion: CAS the item field to null. That single CAS removes the element from the collection for every other thread, even though the node is still linked into the chain from both directions. Any traversal that meets a null item skips the node.
Stage two is unlinking, which is memory hygiene rather than correctness. The unlink searches outward for the nearest active neighbours, hopping over any dead nodes it meets on the way, then repairs both directions: CAS the predecessor's next link to skip the dead node, and CAS the successor's prev link to skip back. Skipping several dead nodes with one CAS is where the term hop comes from.
One repaired direction is not an unlink. If only the predecessor were CASed, the two directions would disagree: forward traversal would skip the corpse while backward traversal still walked through it, and an algorithm that switches direction, which the unlink search itself does, could visit a node twice or miss a live one entirely. Both neighbours have to be repaired before the node is unreachable from the live part of the list.
The implementation is also allowed to skip the repair. It counts the hops an unlink would need and can decline when the node sits near an end and the run of dead nodes would be cheap to walk past, because nothing about correctness depends on the unlink happening. The final stage, gc-unlinking, rewires dead nodes to point at themselves or at terminators so they stop pinning live nodes against the garbage collector; a traversal that meets such a self-link has fallen off the list and restarts from the head.
Marking is instant and mandatory; unlinking is opportunistic and deferred. Correctness lives in the item CAS, and the link repairs only keep the list tidy for the next walk.
ConcurrentLinkedDeque · deleting one node
mark first, then repair both directions
CAS 1 · forward repair
cas(B.next, C → D)
The predecessor skips the corpse: forward traversal stops visiting the dead node. On its own, this is only half the job.
CAS 2 · backward repair
cas(D.prev, C → B)
Without this one the list disagrees with itself: one direction skips the dead node while the other still walks through it.
why one CAS is not an unlink
Repair one side only and an algorithm that switches direction, which the unlink search itself does, can visit a node twice or miss a live one. That is why deletion is staged: null the item first, then repair both links, and let the repair be deferred when the hops are not worth it.
Play: two threads, two ends
The player runs the whole story: two threads working opposite ends, an interior removal that is marked and then unlinked in two steps, the half-repaired state that a single CAS would leave behind, and the deferred repair that the implementation is allowed to skip. The amber marker on the half-repaired step is the hazard, not a crash: the animation never leaves the deque corrupted, because the real code never lets the corrupt state persist.
Watch the two lanes as they diverge. Opposite ends mean the CASes almost never meet. The one step where they both push at the front is the retry lesson: one CAS wins, the loser re-reads and tries again, and the operation is allowed to repeat itself.
Deletion is a mark plus two link repairs; the retry is what you pay when two threads touch the same end.
ConcurrentLinkedDeque · two threads, two ends
idle
idle
Start: the deque is empty. Either end can take the next element, both operations are CAS loops over the same chain, and neither of them ever blocks.
What it costs, and what it refuses to promise
The bill is the same as the queue's, plus interest on the second direction.
- size() is a walk. No counter, so counting means traversing; the number may be stale by the time it returns, and it is not useful under mutation. The lock-free queue makes the same trade for the same reason.
- Iterators are weakly consistent. No ConcurrentModificationException and no snapshot: an element present for the whole traversal is seen exactly once, later additions may or may not appear, and two passes can disagree.
- Nulls are rejected by every add, with NullPointerException, because poll already uses null to mean empty.
- Unbounded. No capacity and no backpressure; offer never returns false at either end, and nothing here can slow a producer down.
- Two links per node. More memory per element than the queue and one more pointer to chase. Interior removals such as remove(Object) and removeFirstOccurrence walk from an end to find the element, so they are O(n).
- No blocking API. There is no put and no take. When a thread needs to wait for an element, that is LinkedBlockingDeque, not this class.
Both ends are O(1) amortized; everything in the middle is a walk.
Three deques, three answers
The choice is between waiting, one end, and two ends, and the table lines up the three containers people actually compare.
| Container | Ends | Blocking | size() | Reach for it when |
|---|---|---|---|---|
| ConcurrentLinkedDeque | both, lock-free | no: offer and poll only | O(n) walk | both ends must be usable without ever parking a thread |
| LinkedBlockingDeque | both, one lock | yes: put and take at both ends | O(1) count | you want a double-ended work queue and waiting is acceptable, which is most of the time |
| ConcurrentLinkedQueue | one, lock-free | no | O(n) walk | a single FIFO with no blocking; cheaper per operation than the deque |
- Work-stealing pools do not use this class. ForkJoinPool runs its own internal work queues, tuned for its own stealing pattern; the fork-join lesson opens that box.
- Single-threaded code does not use any of the three. ArrayDeque is the default there and beats all of them on overhead; the queue lesson covers it.
- When both ends are needed and blocking is fine, prefer LinkedBlockingDeque. One lock is simpler to reason about, and blocking semantics give you backpressure for free.
One end, two ends, or wait on both: ConcurrentLinkedQueue, ConcurrentLinkedDeque, LinkedBlockingDeque.
Lock-free is not wait-free, and not magic
Lock-free promises system-wide progress: some thread always finishes. It does not promise that your thread finishes. Two threads working the same end can collide, and the loser re-reads and retries; an unlucky operation can repeat several times. That gap has a name, and it is the question to expect: this class is lock-free, not wait-free.
The implementation spends extra CASes to keep retries rare. Hops skip whole runs of dead nodes in one go, end operations start from the nearest active node rather than from an exact pointer, and the pointer repairs of an unlink can be deferred entirely when they would cost more than the walk they save.
The linearizability story is worth knowing precisely, too. Each single-element operation at an end is linearizable, but combinations are not: the class documentation records that an addFirst racing a pollFirst can be observed by an iterator as [A B C] and then as [A C], even though nothing was ever removed from the middle. Iteration is weakly consistent, and a traversal is a witness to a moment, not to a history.
Lock-free does not mean wait-free: any single operation may retry. The design spends hops and deferred repairs to keep that rare, not impossible.
One CAS is not an unlink
The instinct when deleting from a doubly linked list is to patch the predecessor and move on. In a concurrent deque that leaves the successor still pointing backwards at the corpse, and now the list disagrees with itself depending on which direction you walk: the forward links skip the dead node, the backward links still route through it. A traversal that switches direction, which the unlink search itself does, can then see a live node twice or miss one entirely, with no exception anywhere to tell you. The fix is not a bigger CAS. It is the two-stage order: mark the item null first, repair both neighbours after, and let the repair be skipped when it is not worth the walk.
Interview angles
Why is deleting a node harder than adding one in a lock-free deque?+
An element added at an end is published by one CAS on the end node's outward link. A node in the middle is referenced from both neighbours, so removing it has to change two links, and either neighbour may itself be dead while still linked.
The implementation answers that by separating removal into a logical deletion (a single item CAS, the only correctness-critical step) and an unlink (two link repairs performed when they are worth the hops).
How does an interior removal actually proceed?+
CAS the item to null first, which removes the element for every thread instantly. Then search outward for the nearest active neighbours, skipping dead ones, and CAS the predecessor's next and the successor's prev so both directions skip the corpse. Finally gc-unlink the dead node with self-links so it stops keeping live nodes reachable.
Common misconception: That the node disappears when the item becomes null. Correctness is done at that instant, but the node can stay linked indefinitely; unlinking is deferred and done by whichever thread finds it convenient.
What is a hop, and why defer the unlink?+
A hop is skipping one or several already-dead nodes inside a single CAS while searching for a live neighbour. The implementation counts how many hops a repair would cost and can skip it when the dead run would be cheaper to walk past, because unlinking is memory hygiene, not correctness.
Follow-up: What does gc-unlinking add on top? It rewires dead nodes to point at themselves, so a dead node can no longer retain live ones for the collector.
Why no O(1) size() here either?+
The same trade as the lock-free queue: a counter would be one shared field that every end operation writes, and the class spends a traversal instead. size() walks from the first node and can be stale before it returns.
That is a deliberate exchange rather than a missing feature. A central count would reintroduce exactly the contended hot spot that the CAS-based design exists to remove.
When is LinkedBlockingDeque the better answer?+
Whenever a thread is allowed to wait: one lock, put and take at both ends, an optional bound, O(1) size. Most double-ended work queues are easier to make correct with it, and ConcurrentLinkedDeque is for the cases where blocking is genuinely unacceptable.
Common misconception: That the lock-free deque is simply the modern replacement. It trades blocking for retries and carries a heavier implementation, so one lock is often the better engineering choice.
What does the class not promise?+
Wait-freedom, a snapshot iterator, and linearizability for arbitrary combinations. Single operations at the ends are linearizable, but the documentation records that an addFirst racing a pollFirst can be observed by an iterator as [A B C] and then [A C], with no interior removal involved. Weakly consistent iteration is the honest guarantee.
Follow-up: So how do you write a snapshot when you need one? Copy under an external lock, or use a structure that provides immutable snapshots.