Lesson · Concurrent Collections
ConcurrentLinkedQueue: the lock-free FIFO
15 min readConcurrentLinkedQueue
A FIFO where nobody ever waits: enqueue links a new node with one CAS, dequeue CASes the head item away, and an enqueuer that finds a stale tail helps move it instead of waiting for the thread that stalled. The trade is visible everywhere: size() walks the list, iterators are weakly consistent, and no part of this API applies backpressure.
A FIFO that never makes anyone wait
Every shared queue is a decision about waiting. A synchronized list serialises every access on one monitor, so a fast producer and a fast consumer constantly get in each other's way. A BlockingQueue parks a thread when the queue is full or empty, which is exactly right when waiting is the mechanism you want and exactly wrong when it is not: a thread servicing a network event cannot afford to park inside put, however briefly.
ConcurrentLinkedQueue is the third answer: a FIFO where every operation is a short CAS loop. offer links a new node into a chain and returns, poll detaches the head item and returns, and neither ever parks or waits for another thread to finish. When two threads collide, the loser does not block. It re-reads and tries again. Retrying replaces waiting.
It is a Queue, not a BlockingQueue. There is no put, no take, and no capacity, so offer never returns false: there is no full state to report. Read that as the contract it is. Nothing here slows a producer down, which means backpressure is entirely your problem.
Nothing in ConcurrentLinkedQueue blocks. Progress comes from retrying, never from waiting.
One chain, two pointers that are only hints
The structure is a singly linked list plus two volatile pointers, head and tail. The queue is the chain: an element is in the queue exactly while its node is reachable from head and its item is non-null. An empty queue is not two null pointers, it is a single sentinel node with a null item that both pointers reference.
Both pointers are approximations and are allowed to lag. The Michael and Scott queue from 1996, which this class follows, replaces the rule that tail always points at the last node with a much weaker one: tail can reach the last node in a couple of steps. Fewer invariants to repair means fewer CASes, and fewer CASes is the entire point of the design.
Every mutation is a CAS, and the instant a CAS succeeds is the instant the operation takes effect. That instant has a name you will meet in every lock-free conversation: the linearization point. For an enqueue it is the CAS that links the new node; for a dequeue it is the CAS that nulls out an item.
The list is the queue. head and tail are only where the next operation starts looking.
ConcurrentLinkedQueue · the chain and the two CASes
head and tail are hints; helping keeps them moving
CAS 1 · the mandatory step
casNext(last.next, null → node)
One CAS links the new node after the last one. Success is the linearization point of the enqueue. A failure writes nothing, so the thread re-reads and retries with the same node.
CAS 2 · the optional step
weakCas(tail, stale → node)
Moves the hint only. Failure is ignored on purpose: it means another thread already moved tail, and a stale hint costs nothing but a short walk later.
inset · size() walks
Enqueue: link the node, then move the hint
An enqueue has two jobs, and only the first one is mandatory. The mandatory job is the CAS that changes the last node's next pointer from null to the new node; its success makes the element visible to every other thread and it is the point of no return. The optional job swings tail forward so the next enqueuer starts closer to the end.
The sketch below is the shape of the loop, not the JDK source. Walk from tail to the last node, CAS its link, then move the hint. This read, compute, attempt, re-read cycle is the pattern behind every lock-free structure in java.util.concurrent.
for (Node<E> t = tail, p = t; ; ) { Node<E> next = p.next; if (next == null) { // p is the last node, the only place a CAS can link if (p.casNext(null, newNode)) { // the linearization point: the node is in the queue if (p != t) { tail.cas(t, newNode); // swing the hint; a failure means somebody beat us to it } return true; } // lost the race: another enqueuer linked a node first, so re-read and retry } else { p = (p != t && t != (t = tail)) ? t : next; // prefer a fresh tail over more walking } }
Two CASes at most, and one of them is optional. Missing the link CAS would cost correctness; missing the tail CAS costs the next caller a short walk.
When the tail lags, the enqueuer helps
A stale tail is not an error state, it is the normal state under load. When an enqueuer finds that the node tail pointed at already has a successor, it does not spin on the same link: it walks forward to the real last node and installs its node there. On the way it can swing the tail pointer itself.
That is helping, and it is what makes the algorithm lock-free. A stalled thread holds no lock, so it cannot hold anyone else back: any other thread can finish the work it left behind. The formal promise is that at any moment some thread completes an operation in a finite number of steps.
The weak half of that promise is that the finisher might be somebody else. One particular thread can retry several times before it wins, which is why this queue is lock-free and not wait-free. In the player, p1 and p2 offer while the consumer polls, and every collision resolves as one thread re-reading, never as anyone waiting.
Helping is the price of lock-freedom. Somebody must be able to finish a stalled thread's work, so every operation has to tolerate a half-finished neighbour.
ConcurrentLinkedQueue · two producers, one consumer
idle
idle
idle
Start: the queue is a single sentinel node with a null item, and head and tail both point at it. The first element will be CASed into the sentinel next link.
Dequeue: an item CAS at the head
A dequeue looks symmetric but touches a different field. poll walks from head to the first node with a non-null item and CASes that item to null. The CAS is the linearization point; the node itself usually stays linked for a while afterwards, because in this class deleting an element and unlinking its node are separate events.
If another thread got there first, the losing poll sees a null item, moves on to the next node, and returns null when the chain runs out of live items. An empty queue answers instantly. There is no arm of this API that waits.
Two details keep the structure honest. Old head nodes are self-linked once head moves past them, so a thread traversing through them can notice it has fallen off the list and restart from the head. And the chain threads only through next pointers, which is why every traversal is a pointer chase with the cache working against you.
Deleting the element and unlinking the node are two separate events, and only the first one sits on the critical path of correctness.
What the design costs: size, iterators, memory
There is no counter. A count field would be one shared value that every operation writes, which is exactly the contention this design exists to avoid, so the class spends a traversal instead. size() walks the chain and counts, O(n), and the javadoc is blunt about the rest: it may report a number that was already stale when it returned, and is typically not very useful in concurrent applications.
Iterators are weakly consistent. They never throw ConcurrentModificationException, they may see elements added after they were created, and an element that was present for the whole traversal is returned exactly once. Weakly consistent is not a snapshot, and two passes can disagree with each other.
| ConcurrentLinkedQueue | LinkedBlockingQueue | |
|---|---|---|
| Locking | none: CAS loops | two locks, one for put and one for take |
| Capacity | none, unbounded | optionally bounded; the bound applies backpressure |
| size() | O(n) walk, may be stale | O(1), an internal atomic count |
| Blocking calls | none: offer and poll only | put and take block; offer and poll time out |
| Who waits | nobody, ever | the full or empty side, on purpose |
- Nulls are rejected. offer(null) throws NullPointerException, because poll already uses null to mean empty and the class refuses to make the two states indistinguishable.
- Unbounded means the heap is the bound. If producers outrun the consumer, memory grows until the process dies; shaping that failure is the producer-consumer lesson.
- One node per element, one allocation per insert. Traversal chases pointers through memory, so an array-backed queue pays less per element and pays for it with a lock or a ring protocol.
size() walks the list: no counter, no contention, no cheap answer.
Lock-free, wait-free, and when to choose it
Lock-free means the system always makes progress: whenever any thread takes enough steps, some operation completes. Wait-free is stronger: every thread completes every operation in a bounded number of its own steps. ConcurrentLinkedQueue is lock-free, and a single unlucky operation can retry many times before it wins.
- Reach for it when nobody may wait: an I/O thread enqueueing work, a callback that must not block, many short producers and a consumer that must never park.
- Reach for LinkedBlockingQueue when waiting is the feature: bounded capacity, put and take backpressure, O(1) size, batch drainTo. The blocking queues lesson wires those up.
- Reach for ConcurrentLinkedDeque when both ends are needed without blocking, and expect to pay more per operation than this queue costs.
- Do not reach for any of them when you need a snapshot, a total order over the whole content, or an exact size: iteration here is weakly consistent and size is a wanderer.
Choose this queue when nobody may wait; choose a blocking queue when waiting is the mechanism you actually want.
There is no put() here
The first bug with ConcurrentLinkedQueue is trying to use it as a bounded hand-off. put does not compile, offer never returns false, and a size() check in a retry loop turns a cheap decision into an O(n) walk whose answer was stale before it arrived. If a producer must slow down when work piles up, that is backpressure and this class cannot provide it: use a bounded LinkedBlockingQueue and let the put block. The lock-free queue is for the case where waiting is worse than losing, which is rarer than it feels.
Interview angles
Walk me through an enqueue in ConcurrentLinkedQueue.+
Read the tail hint, walk to the last node, CAS its next link from null to the new node, then swing tail. The link CAS is the linearization point; the swing is an optimisation whose failure is ignored.
If another producer already linked a node, the CAS fails and nothing was written, so the thread re-reads from the node it actually linked onto and retries with the same new node. The loser undoes nothing, because it never changed anything.
Two producers offer at the same instant. What happens to the loser?+
Its CAS fails because the link it targeted is no longer null, so it re-reads the last node and tries again. Nothing is dropped: a failed CAS performs no write, and the same node is simply linked a step later.
Common misconception: That one of the two items is lost. Losing an item would require a write to have happened, and a failed CAS writes nothing.
Follow-up: What if the loser also wanted to swing tail? Its weak CAS fails too, and that is fine: somebody already moved the hint.
Why is size() O(n) here, and would you fix it with a counter?+
There is no count field to read, so counting means walking. A single counter would be one shared hot field written by every operation, which is exactly the contention the design avoids, and the number would still be stale by the time the caller uses it.
The javadoc states it plainly: determining the current number requires a traversal, and the result may be inaccurate if anything changes during it. Treat it as a diagnostic number, never as a control-flow decision.
What does weakly consistent mean for the iterator?+
No ConcurrentModificationException and no snapshot. The iterator reflects some state at or since its creation, returns elements that were present throughout exactly once, and may or may not see later insertions.
That is what lets the class be iterated while producers keep working. Two passes over the same queue can legitimately disagree, which is why weakly consistent iteration is unsuitable when the requirement is a consistent view.
Is the queue wait-free?+
No, it is lock-free. System-wide progress is guaranteed, so some operation always completes, but a given thread can retry several times when it collides with others. Wait-free would bound every operation, which no CAS loop here promises.
Common misconception: That lock-free and wait-free are interchangeable terms. Wait-free is strictly stronger: it bounds the steps of every operation, not just guarantees that somebody wins.
When would you take LinkedBlockingQueue despite the lock?+
When you need waiting itself: a bounded capacity for backpressure, put and take that block, timeouts, O(1) size, or a batch drainTo. Two locks keep producers and consumers mostly independent, and under real load that can beat a CAS loop.
The two classes are different waiting policies rather than rivals: one refuses to wait, the other makes waiting safe and cheap. Pick the policy the producer and consumer need.