Sweaty Imposter

Compare-And-Swap (CAS) / Atomics

TechniqueConcurrencySeniorStaffUpdated
Hardware-level atomic instruction: write a new value only if the current value matches expected; otherwise retry.

When to Use Compare-And-Swap (CAS) / Atomics

Single-word updates (counters, flags, single-pointer head/tail) under contention where a mutex's blocking is overkill. Powers nearly every lock-free data structure.

In Practice

x86 LOCK CMPXCHG, ARM LDREX/STREX. Java's AtomicLong, AtomicReference, LongAdder. Go's sync/atomic. The Linux kernel's atomic_cmpxchg.

Sketch

Java

AtomicLong counter = new AtomicLong(0);

public long incrementAndGet() {
    long cur;
    do {
        cur = counter.get();
    } while (!counter.compareAndSet(cur, cur + 1));
    return cur + 1;
}

How Compare-And-Swap (CAS) / Atomics Comes Up in Interviews

Scenario

Two threads each run 1,000,000 iterations of counter++ on a shared long. The final value is consistently less than 2,000,000. You need it to be exact and the critical section is one instruction. What's the cheapest fix?

counter++ is read-modify-write, non-atomic. An AtomicLong (CAS under the hood) makes the update atomic at hardware speed, far cheaper than a mutex for a single-word update. A mutex would also work but adds blocking; an rwlock is wrong because the operation is a write.

Under heavy contention CAS can livelock-retry. The JDK ships LongAdder which stripes the counter across cells to cut contention, trading exact-now reads for sum-on-read.