Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

Explain the ABA problem with a lock-free stack example, and how Java helps or does not help.

ABA happens when a thread reads a value A, is paused, and meanwhile other threads change it to B and back to A, so the paused thread's compare-and-set succeeds although the state underneath has changed. In a lock-free stack, a thread that planned to swing head from A to A.next can install a next pointer that is no longer valid and corrupt the stack. Java's garbage collector makes this much less likely with freshly allocated nodes, because a node cannot be reused while a thread still references it, but ABA still occurs with value-based state or object pooling, and AtomicStampedReference (a reference plus a version stamp) or AtomicMarkableReference (a reference plus a boolean) are the tools to detect it.

Why this question is asked

Compare-and-set checks that a value is the same as when we read it, and we tend to read that as 'nothing has happened since'. ABA is the case where that reading is wrong. Interviewers ask about it because it is the classic subtle bug in lock-free code, and because the Java answer has a twist that many candidates miss: garbage collection protects the textbook example, but not every program. In this answer, we will recap the lock-free stack, walk through the ABA interleaving step by step, see why Java usually escapes it, look at the cases where it does not, and fix it with a stamped reference.

1A Quick Recap of the Lock-Free Stack

A lock-free stack, often called a Treiber stack, is a linked list of nodes with an AtomicReference pointing at the top node, the head. To pop, a thread reads the head, reads that node's next pointer, and uses compareAndSet to move head from the node it read to that next node. If another thread changed head in the meantime, the CAS fails and the thread retries.

Java
Node h;
do {
h = head.get(); // read head, say node A
if (h == null) return null;
} while (!head.compareAndSet(h, h.next)); // move head from A to A.next, if head is still A
return h.value;

The CAS checks one thing only: that head still refers to the node we read. The whole question is whether 'head is still A' really means 'the stack is still as I saw it'.

2Walking Through the ABA Interleaving

Take a stack with three nodes, A on top, then B, then C. Thread 1 starts a pop: it reads head = A and A.next = B, and is about to CAS head from A to B. At that moment it is paused, perhaps descheduled by the operating system.

While thread 1 sleeps, thread 2 pops A, then pops B, so the stack is just C. Then thread 2 pushes A back, the same node object, which now points to C. The stack is A then C, and head is A again. Thread 1 wakes up and runs its CAS from A to B. Head is A, so the CAS succeeds and head becomes B. But B was popped long ago; it is no longer part of the stack, and its next may point anywhere. C has been lost, and B, which another thread may be using, is back in the stack. The structure is now corrupt, and nothing failed loudly.

Step throughABA in a lock-free pop
Thread 1headThread 2
read head = A, A.next = B
paused
pop A: head = B
pop B: head = C
push A again: A.next = C, head = A
CAS(A, B)
succeeds: head = B (stale)

7 messages in order. Play them, or step through them one at a time.

head went A -> B -> C -> A, so the CAS cannot tell that the stack changed under thread 1.

3Why Java Usually Escapes It

Notice what the example needed: thread 2 pushed back the same node object A. In languages with manual memory management, this happens naturally, because a freed node's memory is quickly reused for the next allocation, so a 'new' node can have the same address as the old one. In Java, as long as thread 1 holds a reference to A in its local variable h, the garbage collector cannot reclaim A. A push that allocates a new node always gets a different object, so the CAS compares two different references and fails, exactly as it should.

So a Treiber stack that allocates a fresh node for every push, and never reinserts nodes, is safe from ABA in Java with no extra work. This is a real benefit of garbage collection for lock-free code, and it is why the JDK's own lock-free structures rarely need stamps.

4When ABA Still Happens in Java

The protection only covers object identity. It vanishes in two common situations. The first is object pooling: to avoid allocation, the code keeps popped nodes in a free list and reuses them for later pushes. Then the same node object really does come back, and the textbook interleaving happens exactly as described.

The second is value-based state, where the CAS is on a value rather than on a freshly allocated object. If an AtomicInteger holds the index of the top slot in a pre-allocated array, the index can go from 5 to 4 to 5 while the content of slot 5 changed. Likewise, an AtomicReference holding a cached Integer or an enum constant can return to the same object because those values are shared. In each case the CAS sees the old value and cannot know what happened in between.

Is this CAS exposed to ABA in Java?
SituationExposed?Why
Fresh node per push, never reusedNoGC keeps old node alive; new node differs
Nodes recycled from a poolYesSame object can return to head
Index into a pre-allocated arrayYesSame int value, different slot content
Reference to cached Integer or enumYesShared instances repeat

5Fixing It With AtomicStampedReference

The general cure is to compare something that never repeats. AtomicStampedReference pairs a reference with an int stamp, used as a version number, and its compareAndSet succeeds only if both the reference and the stamp match. Every successful update increments the stamp, so A at version 7 and A at version 9 are different even though the reference is the same.

Java
AtomicStampedReference<Node> head = new AtomicStampedReference<>(null, 0);
Integer pop() {
int[] stampHolder = new int[1];
while (true) {
Node h = head.get(stampHolder); // reference and stamp read together
int stamp = stampHolder[0]; // for example 7
if (h == null) return null;
if (head.compareAndSet(h, h.next, stamp, stamp + 1)) {
return h.value; // succeeds only if still (A, 7)
} // thread 1 in our story sees (A, 9): CAS fails, retry
}
}

In our story, thread 2's three operations raise the stamp from 7 to 10, so thread 1's CAS expecting (A, 7) fails and it retries with the real state. The cost is that each update allocates a small internal pair object holding the reference and stamp, and the stamp is an int that could in theory wrap around after four billion updates, which is not a concern in practice for one paused thread.

AtomicMarkableReference is the sibling with a boolean instead of an int. It is not a general ABA fix, because a boolean repeats after two changes. Its use is different: lock-free linked lists, such as the Harris list, mark a node's next pointer as 'logically deleted' and swap the pointer and the mark together in one CAS.

6Follow-up questions

Does ConcurrentLinkedQueue suffer from ABA?

No. It allocates a new node for every element and never reuses nodes, so garbage collection gives it the protection we described. That is one reason it can be written with plain CAS on references.

Could a version counter in a long be used instead of AtomicStampedReference?

Yes, when the state fits. For an index-based structure, we can pack a 32-bit index and a 32-bit version into one AtomicLong and CAS both together without allocation. It is faster and common in high-performance libraries, but harder to read.

Is ABA only about stacks?

No. Any CAS that uses 'the value is unchanged' as a proxy for 'nothing happened' can be fooled: free lists, ring buffer indexes and state machines that return to an earlier state. The stack is simply the clearest example.

7Conclusion

In this answer, we saw the ABA problem in a lock-free stack: a paused thread reads head A and plans to install A.next, other threads pop A and B and push A back, and the paused CAS succeeds with a stale next, corrupting the stack. In Java, garbage collection prevents this when every push allocates a new node, because the old node cannot be reused while referenced, but pooling and value-based state bring ABA back. AtomicStampedReference detects it by pairing the reference with a version stamp, and AtomicMarkableReference pairs it with a boolean for logical deletion marks.

What to say in the interviewAbout 100 seconds aloud

Open with

ABA is when compare-and-set is fooled because a value went from A to something else and back to A. With a lock-free stack: thread 1 starts a pop, reads head A and A.next, which is B, and plans to CAS head from A to B, but it's paused.

Then, if they want more

Meanwhile thread 2 pops A, pops B, and pushes A back, so the stack is A then C and head is A again. Thread 1 resumes, its CAS from A to B succeeds because head is A, and now head points at B, a node that was already removed, and C is lost. The stack is corrupt with no error.

Java helps in the common case: if every push allocates a new node, the garbage collector can't reclaim A while thread 1 still holds a reference, so a new node is always a different object and the CAS fails correctly.

But that protection is gone if nodes are pooled and reused, or if the CAS is on a value, like an int index into a pre-allocated array or a cached Integer, because those values genuinely repeat.

The fix is to compare something that doesn't repeat: AtomicStampedReference pairs the reference with an int version, and the CAS checks both and increments the stamp, so A at version 7 isn't A at version 9. AtomicMarkableReference pairs it with a boolean, which is mainly used for logical-deletion marks in lock-free lists, not as a general ABA fix.

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.
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 "Explain the ABA problem with a lock-free stack example, and how Java helps or does not...": https://scrivio-interview-library.netlify.app/java/atomics/1011607855/