Compare-and-set: how atomics work
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Atomic variables do not take a lock. Every update is built on one small operation: compare-and-set, which changes a value only if it still holds what you saw a moment ago. If someone else changed it first, you simply try again.
compareAndSet(expected, newValue)
Compare-and-set updates a variable only if it still holds an expected value, in one atomic step; atomic classes use it to avoid locks.
compareAndSet(expected, newValue), often called CAS, sets the variable to newValue only if its current value equals expected, and returns true. If the value is something else, it changes nothing and returns false. The compare and the set happen as one atomic step.
Example 1 · compareAndSet succeeds only when the value is what you expect
import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicReference;
public class CompareAndSetDemo { public static void main(String[] args) { AtomicInteger seats = new AtomicInteger(3); System.out.println("CAS 3 -> 2: " + seats.compareAndSet(3, 2) + ", seats = " + seats.get()); System.out.println("CAS 3 -> 2: " + seats.compareAndSet(3, 2) + ", seats = " + seats.get()); System.out.println("CAS 2 -> 1: " + seats.compareAndSet(2, 1) + ", seats = " + seats.get());
AtomicReference<String> holder = new AtomicReference<>("FREE"); System.out.println("Claim seat: " + holder.compareAndSet("FREE", "Anu") + ", holder = " + holder.get()); System.out.println("Claim seat: " + holder.compareAndSet("FREE", "Vikram") + ", holder = " + holder.get());
AtomicReference<Integer> fare = new AtomicReference<>(1000); Integer expected = 1000; // a different Integer object System.out.println("CAS with a new Integer 1000: " + fare.compareAndSet(expected, 900)); }}CAS 3 -> 2: true, seats = 2 CAS 3 -> 2: false, seats = 2 CAS 2 -> 1: true, seats = 1 Claim seat: true, holder = Anu Claim seat: false, holder = Anu CAS with a new Integer 1000: false
What this code does
- The first CAS sees 3 and sets 2. The second also expects 3, but the value is now 2, so it fails and changes nothing.
- Anu claims the free seat. Vikram's CAS expects
"FREE"but finds"Anu", so he learns at once that he lost. - The last CAS fails although both numbers are 1000:
AtomicReferencecompares objects with==, and 1000 is outside the small cache of sharedIntegerobjects (-128 to 127 by default).
On most CPUs this is a single machine instruction (for example CMPXCHG on x86), so no lock is involved. It is like booking a seat with the message "book seat 32 only if it is still free": if someone booked it first, your request fails and you know at once. AtomicReference.compareAndSet compares with ==, the same object, not equals. That matters with boxed numbers and new strings.
The retry loop
The CAS retry loop is how every atomic update is built: read the current value, compute the new value from it, then compareAndSet(old, new). If the CAS fails, another thread changed the value in between, so read again and repeat.
int old, next;do { old = seats.get(); // 1. read if (old == 0) return false; // nothing left to book next = old - 1; // 2. compute} while (!seats.compareAndSet(old, next)); // 3. retry if someone got there firstreturn true;No update is ever lost: a CAS that is based on an old value always fails. incrementAndGet(), updateAndGet() and accumulateAndGet() are this loop written for you. That is why the lambda you pass to updateAndGet may run more than once.
Example 2 · A Tatkal booking written as a CAS retry loop
import java.util.concurrent.atomic.AtomicInteger;
class TatkalSeats { private final AtomicInteger seats;
TatkalSeats(int seats) { this.seats = new AtomicInteger(seats); }
boolean book() { while (true) { int old = seats.get(); // 1. read if (old == 0) { return false; } if (seats.compareAndSet(old, old - 1)) { // 2. compute and 3. try to set return true; } // CAS failed: another counter booked in between, so read again } }
int left() { return seats.get(); }}
public class CasLoopDemo { public static void main(String[] args) throws InterruptedException { TatkalSeats train = new TatkalSeats(1000); int[] booked = new int[4]; Thread[] counters = new Thread[4]; for (int c = 0; c < 4; c++) { int id = c; counters[c] = new Thread(() -> { for (int i = 0; i < 400; i++) { if (train.book()) { booked[id]++; } } }, "counter-" + (c + 1)); counters[c].start(); } for (Thread t : counters) { t.join(); } int total = booked[0] + booked[1] + booked[2] + booked[3]; System.out.println("Requests: 1600"); System.out.println("Booked: " + total); System.out.println("Seats left: " + train.left()); }}Requests: 1600 Booked: 1000 Seats left: 0
What this code does
- Each booking reads the seat count, and its CAS succeeds only if no other counter changed it in the meantime. Otherwise the loop reads the fresh value and tries again.
- 1600 requests compete for 1000 seats: exactly 1000 are booked and none are sold twice, without any lock.
- How the 1000 bookings are split between the four counters changes from run to run, so only the total is printed.
Order of execution
Put the CAS retry loop in order
Tap the steps in the order the loop runs them.
Lock-free does not mean wait-free
Lock-free means that whenever threads compete, at least one of them succeeds. No thread holds a lock, so a thread that is paused or slow can never block the others.
Example 3 · Counting failed CAS attempts under contention
import java.util.concurrent.atomic.AtomicInteger;
public class CasRetriesDemo { static final AtomicInteger counter = new AtomicInteger();
public static void main(String[] args) throws InterruptedException { long[] failures = new long[4]; Thread[] threads = new Thread[4]; for (int t = 0; t < 4; t++) { int id = t; threads[t] = new Thread(() -> { for (int i = 0; i < 100_000; i++) { int old; do { old = counter.get(); if (counter.compareAndSet(old, old + 1)) { break; } failures[id]++; // someone else won this round } while (true); } }, "thread-" + (t + 1)); threads[t].start(); } for (Thread t : threads) { t.join(); } System.out.println("Counter: " + counter.get()); for (int t = 0; t < 4; t++) { System.out.println("thread-" + (t + 1) + " failed CAS attempts: " + failures[t]); } }}Counter: 400000 thread-1 failed CAS attempts: 44276 thread-2 failed CAS attempts: 66991 thread-3 failed CAS attempts: 75067 thread-4 failed CAS attempts: 49890
What this code does
- The counter is always exactly 400000: every failed CAS is retried, so no increment is lost.
- The failure counts change on every run and differ between threads. Some thread always wins each round (lock-free), but no thread is promised a quick win (not wait-free).
- When the threads happen to overlap less, for example on a machine with fewer cores, the counts can be much smaller, even 0 for some threads.
Wait-free is a stronger promise: every thread finishes in a limited number of steps. A CAS loop is lock-free but not wait-free. One unlucky thread can fail its CAS again and again while other threads keep winning. In practice CAS loops are very fast when contention is low or moderate. Under very heavy contention, many failed retries waste CPU time; the LongAdder lesson shows one answer to that.
The ABA problem in simple words
The ABA problem: a thread reads value A, another thread changes it to B and then back to A, and the first thread's CAS still succeeds, because the value looks unchanged. CAS checks the value, not the history.
Example 4 · ABA: a plain CAS is fooled, a stamped CAS is not
import java.util.concurrent.atomic.AtomicReference;import java.util.concurrent.atomic.AtomicStampedReference;
public class AbaDemo { static final String FREE = "FREE"; static final String BOOKED = "BOOKED";
public static void main(String[] args) { AtomicReference<String> seat = new AtomicReference<>(FREE); String seen = seat.get(); // agent A reads FREE ... and pauses seat.set(BOOKED); seat.set(FREE); boolean plain = seat.compareAndSet(seen, "Agent A's customer"); System.out.println("Plain CAS succeeded? " + plain + " (missed the booking and cancellation)");
AtomicStampedReference<String> seat2 = new AtomicStampedReference<>(FREE, 0); int[] stampHolder = new int[1]; String seen2 = seat2.get(stampHolder); // agent A reads FREE with stamp 0 int seenStamp = stampHolder[0]; seat2.compareAndSet(FREE, BOOKED, 0, 1); seat2.compareAndSet(BOOKED, FREE, 1, 2); // cancelled: stamp 2 boolean stamped = seat2.compareAndSet(seen2, "Agent A's customer", seenStamp, seenStamp + 1); System.out.println("Stamped CAS succeeded? " + stamped + " (value " + seat2.getReference() + ", stamp " + seat2.getStamp() + ")"); }}Plain CAS succeeded? true (missed the booking and cancellation) Stamped CAS succeeded? false (value FREE, stamp 2)
What this code does
- The two threads are acted out in order inside
main, so the run is the same every time. Agent A readsFREE, then the seat is booked and cancelled before A continues. - The plain CAS only checks that the value is still
FREE, so it succeeds and A never learns about the booking in between. AtomicStampedReferencealso compares the stamp. A expected stamp 0 but finds 2, so the CAS fails and A knows to read the seat again. Booking made the stamp 1 and cancelling made it 2.
For a plain counter this is harmless: 5 is 5. It matters when the same value can mean a different situation, for example a seat that was free, then booked and cancelled, or a reused node in a lock-free linked structure. The fix is to compare a version number (a stamp) along with the value. AtomicStampedReference holds a reference plus an int stamp, and its compareAndSet succeeds only if both still match. Every change increases the stamp, so A-B-A is detected.
Next step
Check your understanding
12 quick questions