Video in progress

Strong Middle 🧵 Concurrency

What is the ABA problem in a CAS operation, and when is it a real risk?

CAS only checks "is the value still A?". If another thread changed the value A→B→A in between, CAS doesn't notice. In lock-free stacks or structures that reuse objects, this can corrupt the structure.

📖 Answer

An example with pop in a lock-free stack:

  1. T1 read the top: top = A, A.next = B. It stopped right there.
  2. T2 popped A, popped B, then pushed A back. Now top = A, but A.next = C.
  3. T1 wakes up and does CAS(top, A, B), which succeeds, because A is on top again. Now top = B, even though B has already been removed from the stack.

Java has a GC, so the classic C/C++ form (memory being freed and a new object appearing at the same address) is less common: as long as T1 holds a reference to A, A isn't collected. The problem mainly shows up when objects are reused from a pool, or when the value is a primitive.

A primitive example: a balance goes 100 → (withdraw) 50 → (top up) 100. If your logic relies on the assumption "if the balance hasn't changed, nothing happened in between", that is a bug.

The solution is to add a version:

AtomicStampedReference<Node> top = new AtomicStampedReference<>(null, 0);

int[] stampHolder = new int[1];
Node current = top.get(stampHolder);
top.compareAndSet(current, current.next, stampHolder[0], stampHolder[0] + 1);

The stamp grows on every change, so A→B→A now becomes (A,1)→(B,2)→(A,3) and CAS catches it. The same idea is used in DB optimistic locking with a @Version column.

In practice you will rarely write your own lock-free structure, since java.util.concurrent has already done it correctly.