Knowledge Guide
HomeConcurrencyConcurrency Foundations

Atomics & Compare-And-Swap (CAS)

Locking without locks

A lock fixes the counter race, but blocking threads is expensive and risks deadlock. For a single shared variable there is a faster tool: atomic types backed by Compare-And-Swap (CAS), a hardware instruction (CMPXCHG on x86) that does a read-check-write as one indivisible step.

What CAS actually does

compareAndSet(expected, newValue): atomically — if the current value still equals expected, set it to newValue and return true; otherwise change nothing and return false.

That boolean is the whole trick. If CAS returns false, another thread changed the value in between, so you re-read and try again. Compare this to the race condition: a plain count++ blindly overwrites; CAS detects the conflict and retries, so no update is lost.

Two threads use CAS: T1 succeeds 0 to 1, T2 fails its 0 to 1 because the value is now 1, then re-reads and succeeds 1 to 2, final value 2
Two threads use CAS: T1 succeeds 0 to 1, T2 fails its 0 to 1 because the value is now 1, then re-reads and succeeds 1 to 2, final value 2

The retry loop, traced

#ThreadActioncounter
1T1read → 00
2T2read → 00
3T1CAS(0→1) ✓1
4T2CAS(0→1) ✗ (value is 1, not 0)1
5T2re-read → 11
6T2CAS(1→2) ✓2

incrementAndGet() is exactly this loop, hidden:

// what AtomicInteger.incrementAndGet() does internally
int v;
do {
    v = get();                  // read current
} while (!compareAndSet(v, v + 1));   // retry until our read was still valid
return v + 1;

Lock-free vs locked — when to use which

Atomic / CASLock
ScopeOne variableAny multi-step critical section
BlockingNo — spins & retriesYes — threads park
Best whenCounter, flag, single reference; low–moderate contentionMultiple fields must change together; high contention
RiskWasted CPU on retries under heavy contentionDeadlock, lock convoy

The classic gotcha: the ABA problem

CAS only checks the value, not whether it changed and changed back. If a value goes A→B→A, a CAS expecting A succeeds — even though the world moved underneath it (common with reused nodes in lock-free stacks). Fix with a version stamp: AtomicStampedReference compares (value, stamp).

Takeaways


Re-authored for this guide; CAS retry diagram hand-authored as SVG. Follows Java Concurrency in Practice (ch. 15) and Jenkov's non-blocking-algorithms tutorial. See also: Race Conditions, and Memory Model & Visibility.

🤖 Don't fully get this? Learn it with Claude

Stuck on Atomics & Compare-And-Swap (CAS)? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Atomics & Compare-And-Swap (CAS)** (Concurrency) and want to truly understand it. Explain Atomics & Compare-And-Swap (CAS) from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Atomics & Compare-And-Swap (CAS)** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Atomics & Compare-And-Swap (CAS)** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Atomics & Compare-And-Swap (CAS)** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes