Quick revision
The short answer
A Treiber stack keeps an AtomicReference<Node> head, where each Node holds a final value and a next pointer. push creates a node, points its next at the current head and uses compareAndSet to make it the new head, retrying if head changed; pop reads head, returns null if it is empty, and uses compareAndSet to move head to head.next, retrying on failure. It is correct because each CAS succeeds only if head is unchanged since it was read, so concurrent updates force a retry instead of being lost, and AtomicReference's volatile semantics safely publish each pushed node to the threads that pop it.
What to remember
In this answer, we built a Treiber stack from a Node with a final value and a next pointer and an AtomicReference head. push sets the new node's next to the current head and CASes head to the node; pop CASes head from the top node to its next and returns the value, returning null on an empty stack. It is correct because each CAS succeeds only if head is unchanged since it was read, giving every operation a single linearization point, and it is safe because AtomicReference's volatile semantics publish the node's fields. With fresh nodes and garbage collection, ABA cannot occur.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A Treiber stack keeps an AtomicReference<Node> head, where each Node holds a final value and a next pointer. push creates a node, points its next at the current head and uses compareAndSet to make it the new head, retrying if head changed; pop reads head, returns null if it is empty, and uses compareAndSet to move head to head.next, retrying on failure. It is correct because each CAS succeeds only if head is unchanged since it was read, so concurrent updates force a retry instead of being lost, and AtomicReference's volatile semantics safely publish each pushed node to the threads that pop it.
Background to this question
The Treiber stack, named after R. Kent Treiber who described it in 1986, is the smallest useful lock-free data structure, which makes it the standard way to test whether someone understands compare-and-set. It is short enough to write on a whiteboard, yet explaining why it is correct touches atomicity, memory visibility and the ABA problem. In this answer, we will set up the node and the head, write push and pop step by step, explain why each one is correct under concurrency, look at how nodes are safely published to other threads, and see where ABA fits in Java.
1The Building Blocks: Node and Head
A stack is a linked list where we only add and remove at the top. Each node holds a value and a reference to the node below it. The whole stack is identified by a single reference to the top node, which we call head. If we can change head atomically, we can change the stack atomically, so head is an AtomicReference<Node>, a reference that supports compareAndSet: 'set it to the new node, but only if it still points at the node I expect'.
One detail differs from the way the question phrases it. The value can be final, but next cannot be final in this version of push, because we set it inside the retry loop, possibly more than once, before the node becomes visible. That is safe because no other thread can see the node until our CAS publishes it. If we want next to be final too, we create a new node on each attempt inside the loop, which costs an allocation per retry.
2Writing push
To push, we create a node for the value. Then we loop: read the current head, point our node's next at it, and try to swing head from what we read to our node. If another thread pushed or popped in between, head is no longer what we read, the CAS fails, and we try again with the new head.
Notice the reason the loop rereads head and resets n.next every time: if we kept the old next after a failed CAS, our node would point below a node that another thread just pushed, and that node would vanish from the stack.
3Writing pop
To pop, we read head. If it is null, the stack is empty. Otherwise we try to swing head from that node to its next. If the CAS succeeds, the node is ours and we return its value; if it fails, someone else changed the top and we try again.
9 messages in order. Play them, or step through them one at a time.
The losing thread retries with the new head, so neither push is lost.
4Why It Is Correct
The key is that every change to the stack is a single CAS on head, and a CAS succeeds only if head still holds the exact node the thread read. So a thread's update is always computed from the latest state: for push, our next equals the current top at the instant we install our node; for pop, the next we install is the next of the node that really is on top at that instant. Any interference makes the CAS fail, and the thread recomputes from fresh state. No update can overwrite another.
We can also name the moment each operation takes effect, called its linearization point: the successful CAS for push and for a non-empty pop, and the read of a null head for an empty pop. Every concurrent history then behaves as if the operations ran one at a time in the order of those points, which is the definition of a correct concurrent stack. And it is lock-free: a CAS fails only because another thread's CAS succeeded, so some thread always makes progress, and a paused thread never blocks the others.
5Safe Publication Through the AtomicReference
There is a second, quieter question: when thread 2 pops a node that thread 1 pushed, is it guaranteed to see the node's value and next, which thread 1 wrote with ordinary field writes? Yes. AtomicReference has volatile semantics: a successful compareAndSet acts as a volatile write, and get() acts as a volatile read. The Java Memory Model says that everything a thread wrote before a volatile write is visible to any thread that reads that value with a volatile read. Thread 1 wrote value and next before its CAS, thread 2 reads head with get(), so thread 2 sees both fields fully initialised.
That is why the node fields need no volatile modifier and no locking. It is also why reading the fields of h after the CAS in pop is safe: they were written before the node was published, and nobody changes them afterwards.
6What About ABA?
The classic worry for this algorithm is ABA: a pop reads head A and A.next B, pauses, and other threads pop A and B and push A back, so the paused CAS succeeds with a stale next. In Java that cannot happen with this code, because push always allocates a fresh node and the garbage collector will not reclaim node A while the paused thread still references it. A later push therefore produces a different object, and the paused CAS fails as it should.
The protection disappears if someone 'optimises' the stack by recycling nodes from a pool. Then ABA comes back, and the fix would be a version stamp, for example AtomicStampedReference. So in a review, the comment next to this class should say: nodes must never be reused.
7Follow-up questions
Is this stack faster than a synchronized one?
Under low contention they are similar. Under heavy contention on many cores, both suffer from all threads hitting one head variable; the lock-free version never blocks, but it can waste work on retries. For real use, ConcurrentLinkedDeque or a queue from java.util.concurrent is usually a better choice than either.
How would you test it?
With a stress test where many threads push known values and pop concurrently, then check that every pushed value is popped exactly once, and with jcstress, which runs small concurrent scenarios millions of times and reports forbidden outcomes such as a value popped twice.
Why does pop read h.next inside the CAS call and not earlier?
It reads h.next at the time of the CAS attempt, after reading h, in the same iteration. Since next is never changed after the node is published, the value is stable; what the CAS verifies is that h is still the top, which makes that next the correct new head.
8Conclusion
In this answer, we built a Treiber stack from a Node with a final value and a next pointer and an AtomicReference head. push sets the new node's next to the current head and CASes head to the node; pop CASes head from the top node to its next and returns the value, returning null on an empty stack. It is correct because each CAS succeeds only if head is unchanged since it was read, giving every operation a single linearization point, and it is safe because AtomicReference's volatile semantics publish the node's fields. With fresh nodes and garbage collection, ABA cannot occur.
Open with
The stack is a linked list with an AtomicReference to the top node. A node has a final value and a next pointer. For push, I create the node, then loop: read head, set node.next to it, and compareAndSet head from what I read to my node; if the CAS fails, someone changed the top, so I reread and reset next.
Then, if they want more
For pop, I loop: read head, return null if it's null, otherwise compareAndSet head from that node to its next, and on success return the node's value.
The correctness argument is that every change to the stack is a single CAS on head, and a CAS only succeeds if head is still exactly the node the thread read, so each update is computed from the current state and concurrent updates make the others retry instead of being lost.
Each operation takes effect at its successful CAS, which is its linearization point, and it's lock-free because a CAS only fails when another thread's succeeded.
Visibility comes from AtomicReference's volatile semantics: the pusher writes value and next before the CAS, which acts as a volatile write, and the popper reads head with a volatile read, so it sees the fields fully initialised without the node fields being volatile.
One small point: next can't be final if I set it inside the retry loop, which is fine since the node isn't visible until the CAS. And ABA isn't a concern here because push always allocates a new node and the GC won't reuse one that another thread still references, as long as nobody adds node pooling.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement push and pop for a lock-free stack (Treiber stack) using AtomicReference and...": https://scrivio-interview-library.netlify.app/java/atomics/0b6879454e/