What is compare-and-swap (CAS) and how does it enable loc… — Cracked Java
// Concurrency & Multithreading · Atomics & Compare-And-Swap
MidTheoryBig TechAmazonGoogle

What is compare-and-swap (CAS) and how does it enable lock-free updates?

Compare-and-swap (CAS) is an atomic CPU instruction that updates a memory location only if it still holds an expected value, returning whether the write succeeded. It lets threads coordinate on a hardware primitive instead of a lock, enabling lock-free updates.

The three operands

CAS takes a location, an expected value, and a new value. In one uninterruptible step the hardware checks location == expected and, if true, writes new. It compiles to lock cmpxchg on x86 and a load-linked/store-conditional pair on ARM/POWER. Because it is atomic at the hardware level, no two threads can both "win" the same swap.

The retry loop

A single CAS rarely stands alone — you wrap it in a read-modify-CAS loop. Read the current value, compute the next one from it, then CAS. If another thread changed the field first, the CAS fails (the field no longer equals what you read), and you loop with the fresh value. This is exactly what AtomicInteger.incrementAndGet does:

// Conceptually what getAndAdd does inside AtomicInteger
public int getAndAdd(int delta) {
    int prev, next;
    do {
        prev = get();          // volatile read
        next = prev + delta;
    } while (!compareAndSet(prev, next));  // retry on contention
    return prev;
}

Why it enables lock-free progress

A lock blocks: a thread that holds it can be descheduled, stalling everyone waiting. CAS never blocks — a failed CAS just means someone else made progress, so the system as a whole always advances (this is the "lock-free" guarantee). No context switches, no deadlock, no priority inversion. CAS also carries volatile-strength memory semantics: a successful CAS establishes a happens-before edge, so you get visibility and ordering for free.

The catch: CAS compares values, not histories, so it is blind to a value that changes A → B → A (the ABA problem), and a hot single field can become a contention bottleneck.

Mark your status