Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    Atomics and Compare-and-Swap

    Compare-and-swap (CAS) is a single CPU instruction: "set this memory location to new, but only if it currently holds expected; tell me whether it

    Chapter 5 of 124 min read

    The Plain Picture#

    Updating the chocolate count on the whiteboard without a marker-lock: "If the board still says 10, change it to 9. If it doesn't say 10 anymore, someone beat me — re-read and try again."

    The Real Names#

    • Compare-and-swap (CAS) is a single CPU instruction: "set this memory location to new, but only if it currently holds expected; tell me whether it worked." It's atomic in hardware.

    • Java's atomic classes — AtomicInteger, AtomicLong, AtomicBoolean, AtomicReference — use CAS to offer thread-safe operations without locks: incrementAndGet(), addAndGet(n), compareAndSet(expected, new), updateAndGet(f), accumulateAndGet(x, f).

    • Lock-free code built this way never blocks a thread; threads that lose a race just retry.

    Under the Hood — "spend the last credit" without a lock#

    Eight concurrent requests try to spend from a balance of 3 credits:

    Java
    AtomicInteger credits = new AtomicInteger(3);
    ... each of 8 tasks runs:
    while (true) {
        int cur = credits.get();
        if (cur == 0) return false;                         // nothing left → refuse
        if (credits.compareAndSet(cur, cur - 1)) return true;   // succeeded only if nobody changed it meanwhile
    }                                                       // otherwise loop and re-read
    Output
    CAS: granted 3 of 8 requests, credits left 0

    Exactly 3 granted, never 4, never negative — the "check then act" (cur > 0, then subtract) is safe because the CAS fails if the value changed between the check and the write. This is the thread version of the database race in Operating Systems Ch 8.

    Under heavy contention, many threads retrying the same CAS waste CPU. LongAdder spreads a counter over several internal cells (one per contending thread, roughly) and adds them up on read — much faster for "count lots of events" and slower to read. Use AtomicLong for exact values you read often, LongAdder for high-traffic metrics counters.

    The ABA problem (occasionally asked): a value changes A → B → A between your read and your CAS, so the CAS succeeds even though things changed. AtomicStampedReference adds a version number to detect it. It matters mostly for lock-free data structures.

    Check yourself

    4 questions
    1

    What does compare-and-swap do?

    Show answer

    Atomically sets a variable to a new value only if it still has the expected value, reporting success or failure.

    2

    Why can the credit-spending loop never grant 4 requests?

    Show answer

    Each decrement only succeeds if the value is unchanged since it was read; any concurrent change makes the CAS fail and the thread re-reads, so the count never goes below 0.

    3

    AtomicLong vs LongAdder?

    Show answer

    AtomicLong is a single CAS-updated value (fast reads, contention on writes); LongAdder spreads writes across cells (fast under contention, slower sums).

    4

    What is the ABA problem?

    Show answer

    A value changes and changes back between a read and a CAS, so the CAS wrongly succeeds; version stamps detect it.