Lock-Free Stack (Treiber Stack)

Hard
ConcurrencyLock-FreeCASAtomicReferenceABA ProblemNon-Blocking

Problem Statement

Implement a lock-free, concurrent stack using only atomic Compare-And-Swap (CAS) operations — no locks, no synchronized blocks. This is known as the Treiber Stack. Additionally, identify and address the ABA problem.

class LockFreeStack<T> {
    public void push(T value) {}         // Non-blocking push
    public T pop() {}                    // Returns null if empty (non-blocking)
    public T peek() {}                   // Returns top without removing
    public boolean isEmpty() {}
    public int size() {}                 // Approximate (not linearizable)
    
    // Demonstrate ABA problem
    public void pushWithABAProblem(T value) {}
    // ABA-safe variant using AtomicStampedReference
    public void pushABASafe(T value) {}
    public T popABASafe() {}
}

Key Entities

  • AtomicReference<Node<T>> head: The stack's top, updated with CAS.
  • Node<T>: Immutable node with value and next pointer.
  • CAS loop: Optimistic retry loop: read head, build new node, CAS head to new node.
  • AtomicStampedReference: Used in the ABA-safe variant to detect hidden changes.

Requirements

  1. push() and pop() must be lock-free (no mutexes or synchronized blocks).
  2. Correctness under high contention (many threads pushing/popping simultaneously).
  3. Explain and demonstrate the ABA problem with a concrete example.
  4. Implement ABA-safe variant using AtomicStampedReference.
  5. Characterize the progress guarantee: lock-free (some thread always makes progress) vs. wait-free.

Asked at: Google, Amazon, Microsoft, Palantir, Two Sigma, Jane Street

!Constraints

- All operations use only atomic primitives (no locks). - Must be correct under any thread interleaving. - ABA demonstration must show a scenario where naive CAS succeeds but is semantically wrong. - size() is best-effort (allowed to be approximate); isEmpty() should be accurate. - Memory reclamation: note hazard pointers / epoch-based reclamation as follow-up.
Output

Run or submit your code to see output here.