Lesson · Java Memory Model (JMM)
Atomics & CAS: compare-and-swap, retries and the cost of sharing
16 min readAtomic Classes & CAS
The atomics replace locks with optimism: read a value, compute the next one, and swap it in only if nothing changed in between. A failed swap writes nothing, so the loop retries and a lost update becomes wasted work instead of a lost write. The same primitive explains ABA, false sharing and VarHandle.
The update that keeps getting lost
Two threads increment a shared counter and one write vanishes. The race-conditions lesson replays that interleaving; synchronized closes it by making one thread wait for the other. The atomics answer a different question: what if nobody should wait?
An atomic class gives one variable a read-modify-write operation that other threads cannot interleave with, and it does so without a monitor. No thread blocks, no thread is parked, and both threads stay eligible to run. The machine instruction that makes this possible is what the rest of the lesson is about, because every atomic class is a wrapper around it.
Locks block, CAS retries. Which of the two is cheaper depends on contention, and the atomics win exactly where the critical section is one small update on one value.
compareAndSet: one step, two outcomes
The primitive is compareAndSet(expected, update). It writes update only if the current value is still expected, and it returns a boolean: true means the swap happened, false means the value was not what you thought and nothing was changed.
The hardware provides this as a single indivisible step. On x86 it is a locked cmpxchg; architectures with load-linked/store-conditional instructions build it from an LL/SC pair. Either way, no other thread can act between the comparison and the write, and that is what makes it usable as the base of everything else.
- It never blocks. A failed compareAndSet returns false immediately; waiting is not part of the operation.
- Failure is information. False means the world moved: your expected value is stale, and the correct response is to re-read, not to sleep.
- Success is a claim about the exact value. For references the comparison is identity, meaning the same object, not equals.
CAS is optimistic: if the world changed, start over. The operation assumes nothing moved, checks, and tells you when it was wrong. Every class in java.util.concurrent.atomic is a coat of paint over this one primitive.
CAS · one cell, three outcomes
compare and swap happen as one indivisible stepwhat the cell decides
outcome 1 · match
cell equals expected, so update is written and true comes back.
outcome 2 · stale plan
cell moved, so nothing is written and false comes back. The caller re-reads and recomputes.
outcome 3 · ABA
value went 0 → 1 → 0, so the expected value matches again although the state moved. A stamp is what remembers.
inset · why LongAdder stripes
sum() reads every cell and adds them up. A single AtomicLong would have every writer retrying on the same hot cell, and likely the same cache line; striping trades an exact current value for throughput.
The loop shape to internalise
CAS alone cannot increment: it compares and swaps, it does not add. The addition lives in the loop you write, or in the loop the library writes for you: read the current value, compute the next one, try to publish it, and go back to the read when the publish fails.
int prev, next; do { prev = counter.get(); // 1. snapshot next = prev + 1; // 2. compute from the snapshot } while (!counter.compareAndSet(prev, next)); // 3. publish, or start over // counter.incrementAndGet() is this exact loop, provided so you do not write it
- Two threads both read 0. Each computes 1 and holds the same plan: publish the transition 0 -> 1.
- T1 runs compareAndSet(0, 1). The cell still holds 0, so the comparison passes and the swap runs. The cell is 1.
- T2 runs compareAndSet(0, 1). The cell holds 1, not 0, so the comparison fails and no write happens. T2 has lost nothing, because nothing of T2 was written.
- T2 re-reads: 1. It computes 2 and publishes compareAndSet(1, 2), which succeeds.
- Two increments ran and the cell moved twice. The lost update became wasted work, which is the design: the only iterations that repeat are the ones whose writes never happened.
A lost update becomes wasted work, never a lost write. When the CAS fails, your write did not happen, so re-reading and recomputing from fresh state is always safe.
The class tour
Each class in the package wraps one value (or one array element) and exposes the operations that are worth having. The table is the map; the notes under it are the two or three facts people get wrong.
| Class | What it updates atomically | Reach for it when |
|---|---|---|
| AtomicInteger / AtomicLong | one int or long | counters and single-value state; incrementAndGet, getAndUpdate, updateAndGet, accumulateAndGet |
| AtomicReference of V | one reference | a whole immutable value swapped in one step, with a CAS loop over the snapshot |
| AtomicIntegerArray / AtomicLongArray | one element at an index | element-level atomicity, where a volatile int[] would only make the array reference volatile |
| AtomicBoolean | one boolean | a one-shot latch: compareAndSet(false, true) makes exactly one thread the winner |
| AtomicStampedReference of V | a reference plus an int stamp | the ABA fix: value and version travel together in one CAS |
| AtomicMarkableReference of V | a reference plus one mark bit | the simplified stamped reference, when a single bit of extra state is enough |
| LongAdder / DoubleAdder | a striped sum | statistics with many writers and rare reads: the cells are summed when a reader asks |
| AtomicIntegerFieldUpdater and friends | one volatile field of an existing class | when layout forces you to keep the field as it is; the field must be volatile |
- incrementAndGet / decrementAndGet: the compound shortcuts, with the retry loop inside.
- getAndUpdate(function) / updateAndGet(function): read, apply the function, CAS, repeat on failure. The function may run more than once, so it should be side-effect free.
- accumulateAndGet(x, function): combine a new value with the current one under the same loop, for example Math::max for a high-water mark.
The function in updateAndGet is a candidate, not a command. Under contention it can be called several times before one attempt wins; give it a pure computation and let the library own the retry.
ABA: when the same value is not the same state
CAS compares values. If the cell goes 0 -> 1 -> 0 between your read and your swap, your compareAndSet(0, 1) finds the 0 it expected and succeeds, even though the state moved twice underneath you.
For a counter this is harmless: the number only means itself, and returning to 0 really is returning to 0. It stops being harmless when the value carries identity. The top of a lock-free stack is a reference, and if the head node left and came back, the identity comparison passes while the links around it changed completely.
The fix is to compare more than the value: keep a version stamp beside it and advance the stamp on every write, so a round trip leaves a trace. AtomicStampedReference pairs a reference with an int, compareAndSet takes the expected reference and the expected stamp, and the stale attempt fails on the stamp.
ABA is a fact about values, not a bug in CAS. Decide whether your algorithm cares about history or only about the current state; if it cares, stamp it.
CAS player · one cell, two threads
cell value
0
about to increment
about to increment
Two threads run the same CAS loop: snapshot the cell, compute the next value, publish with compareAndSet. The cell is 0.
Scene 1 is the loop working: a failed CAS writes nothing and the retry costs one computation. Scene 2 is the same round trip without a stamp, where a stale plan is accepted. Scene 3 is the stamp refusing it.
False sharing: the cost of sharing a cache line
Atomicity is not the only thing threads share. Memory moves between cores in cache lines, typically 64 bytes. Two independent atomics that happen to live in the same line keep invalidating each other as their owners write, so the line ping-pongs between cores while the fields are logically unrelated. That is false sharing, and it costs throughput with no correctness symptom at all.
- LongAdder stripes on purpose: each writer lands on a different cell, usually on a different line, and sum() walks the cells when a reader asks. That is why it scales where one AtomicLong retries on one hot line.
- @Contended pads a field out to its own line. It lives in jdk.internal.vm.annotation, and in user code it is disabled unless the JVM is started with -XX:-RestrictContended. Libraries use it inside their own classes; application code rarely needs to.
- Padding is a layout decision, not a semantic one: it only changes performance. If you have not measured a problem, it is not your problem.
Two threads writing two unrelated atomics can still slow each other down. Cache-line sharing is a cost that no lock and no CAS will mention, and the tools that manage it, striping and padding, are about layout rather than about atomics.
VarHandle: the primitive under the primitives
Since Java 9, VarHandle (JEP 193) is the supported way to name a field, array element or static field and choose the memory semantics of each access. The atomic classes are built on it, and it exposes the lower-level modes they do not.
- plain: an ordinary read or write, with no ordering guarantees beyond the usual ones. A 64-bit value can still tear, exactly like a plain field.
- opaque: atomic for that single variable with no ordering relative to other memory. Other threads eventually see the write, and a read never sees a torn value.
- acquire / release: the pair you met with volatile. A release orders prior actions before it; an acquire orders later actions after it.
- volatile: acquire and release in one access, the full volatile semantics.
- compareAndSet and getAndAdd: atomic read-modify-write modes, performed under the ordering you name.
A VarHandle is meant to be a constant. Keep it in a static final field so the JIT can treat the access as a known operation and fold it into the right instruction; a handle stored in a mutable field is just a slower path to the same memory.
When not to use atomics
The atomics protect one variable. The moment an invariant spans two, the shape breaks: transferring a value between two AtomicIntegers is two CASes, and a thread can observe the half state between them.
The list of shapes that want a lock instead is short. A multi-variable invariant needs a lock unless both variables can live inside one immutable value swapped by a single CAS. A critical section that does real work needs a lock, because a CAS loop that keeps failing under contention burns CPU where a parked thread would not. And an atomic read is a snapshot of one value, never of the world around it.
- One variable: atomics, and a CAS loop when the operation is not one of the built-ins.
- One invariant across fields: a lock, or the whole state packed into an immutable value swapped atomically by AtomicReference.
- Long or blocking critical sections: a lock. A retry loop is for updates that almost always succeed on the first attempt.
One variable: atomics. One invariant across fields: a lock, or a single immutable value swapped atomically. The line is that crisp, and every clever half-measure in between is how bugs get in.
CAS protects a cell, not an invariant
Two AtomicIntegers and a transfer: debit one, credit the other. Each step is perfectly atomic, and a thread that reads between them sees money that left nowhere and arrived nowhere. There is no compareAndTransfer; CAS compares one value and swaps one value. Either guard both fields with one lock, or pack them into a single immutable object and swap that object in one AtomicReference. The failure mode is quiet, because no individual operation is wrong, only the pair.
Interview angles
What does compareAndSet do, and what does it return?+
It compares the current value with the expected value and writes the update only if they match, in one indivisible step. The boolean return tells you which outcome happened: true means the swap ran, false means the value had moved and nothing changed.
Hardware implements it directly (a locked cmpxchg on x86, an LL/SC pair elsewhere), which is why it never blocks and never needs a retry inside the primitive itself. For references, the comparison is identity.
Common misconception: That a false result means a failure to handle. It means the caller had a stale snapshot, and the correct reaction is a re-read.
Why is the CAS retry loop correct?+
Because a failed CAS performs no write. Nothing of yours is in the cell, so re-reading the current value and computing a fresh transition loses nothing; the only cost of the collision is one repeated computation.
That is the same lost update from the race-conditions lesson with the loss removed: two threads still compute from the same snapshot, but only one transition is published, and the other thread starts again from the state that won.
int prev, next; do { prev = counter.get(); next = prev + 1; } while (!counter.compareAndSet(prev, next));
Follow-up: What changes under very heavy contention? The loop can spin many times; at that point a lock, or a striped adder, can be the better shape.
What is the ABA problem, and how do you fix it?+
A value that leaves and returns looks unchanged to a value-only comparison, so a stale CAS succeeds although the state moved. Keep a version stamp next to the value and compare both, which is what AtomicStampedReference is for.
Counters do not care: 0 that became 1 and returned to 0 is a 0. Structures that carry identity do care, because the head reference can be the same object again while the links around it changed, and the stale operation then proceeds on an assumption that is no longer true.
Follow-up: What is the cheaper variant when one bit of extra state suffices? AtomicMarkableReference.
AtomicLong or LongAdder?+
AtomicLong when you need the current value and the CAS loop semantics. LongAdder when many threads update and few read: writes spread over cells, and sum() adds them up when asked.
The trade is that LongAdder gives up a single authoritative cell, so it cannot be the target of compareAndSet and its sum is a snapshot of several cells rather than an atomic read. LongAdder is for statistics, not for state machines.
Common misconception: That LongAdder is simply the newer, faster AtomicLong. It is the better shape for one workload and the wrong shape for another.
Why do VarHandles belong in static final fields?+
So the JIT can treat the handle as a constant and compile each access into the intended instruction. A handle held in a mutable field cannot be constant-folded as reliably and loses the benefit of the abstraction.
VarHandle also adds access modes that the atomic classes do not expose, opaque and release among them, which is why library code reaches for it when it needs exact semantics rather than a convenient counter.
Follow-up: Which Java version introduced VarHandle? Java 9, under JEP 193.
When would you not use an atomic?+
When the invariant spans more than one variable (a lock, or one immutable value swapped atomically), and when the critical section does real work rather than one small update. Atomics make single-variable updates lock-free; they do not make a block atomic.
The failure is quiet because every individual operation succeeds: a transfer between two atomics is two correct steps with a window in the middle. Atomicity is a property of an operation, and nobody promised it across two of them.