TL;DR
Compare-and-swap, usually written CAS, is a single instruction that checks a memory location and writes to it in one indivisible step. The thread names the value it expects to find. If the location still holds that value, the new value is written and the instruction reports success; if not, nothing changes and the thread tries again. This lets threads update shared data without a lock, and it is the building block of many lock-free data structures.
Builds on: Race Condition, Thread · Leads to: Wait-Free Synchronization, Linearizability
Where it's used
Standard libraries in Java and Go. Java's AtomicInteger has a compareAndSet method, and the ConcurrentLinkedQueue class, a thread-safe Queue, is built on compare-and-set on its node pointers. Go's sync/atomic package offers CompareAndSwap functions for integers and pointers. Code that counts events on many processor cores often uses these instead of a lock, because a lock makes every core wait in turn.
Operating-system kernels. An operating-system kernel must update shared state from interrupt handlers, which cannot wait for a lock. If the handler interrupted the very code that holds the lock, the handler would wait forever. A compare-and-swap never waits, so the kernel uses atomic compare-and-exchange operations for counters and list pointers.
Databases and cloud key-value stores. Many stores support conditional writes: "write this record only if its version is still 7". Amazon DynamoDB, for example, lets a write carry a condition that makes it fail when the item has changed. This is the same idea as CAS, applied to a stored record instead of a processor word.
How it works
Take one shared counter, , that holds 5, and two threads, A and B, that each want to add 1 to it. A Thread that uses CAS does not hold a lock. It reads the counter, computes the new value, and then asks the hardware to write it only if the counter has not changed since the read. Recall that a race happens when two threads read the same value and then both write, so one write overwrites the other. CAS turns that second write into a test that can fail.
- Both threads read. A reads the counter and gets 5. B reads the counter and also gets 5. Check: both threads remember the expected value 5.
- A attempts its write. A asks for "write 6 if the counter holds 5". The counter holds 5, so the test passes, the counter becomes 6, and the instruction reports success. Check: the counter is 6.
- B attempts its write. B asks for "write 6 if the counter holds 5". The counter now holds 6, so the test fails. The counter stays 6, and the instruction reports failure. Check: B's write did not overwrite A's work.
- B retries. B reads again and gets 6, computes 7, and asks for "write 7 if the counter holds 6". The test passes. Check: the counter is 7, which is the correct total for two increments.
sequenceDiagram participant A as Thread A participant C as Counter participant B as Thread B A->>C: read (gets 5) B->>C: read (gets 5) A->>C: CAS expect 5 write 6 (succeeds) B->>C: CAS expect 5 write 6 (fails) B->>C: read (gets 6) B->>C: CAS expect 6 write 7 (succeeds) Note over C: Final value 7
Every thread that uses CAS for an update follows the same pattern, which is a retry loop. The loop reads, computes, and tries to write, and it stops only when the write succeeds:
repeat:
e = read the counter
v = e + 1
try to write v only if the counter still equals e
if the write succeeded, stop; otherwise repeat
Notice what the loop never does: it never waits for another thread. A thread that loses simply does more work and tries again, and at least one thread always succeeds in each round.
The math
Step 2 in symbols: the first write succeeds
Both threads read , so both have the expected value . A's call is . The test is , which is true, so the location becomes and the operation returns true.
Step 3 in symbols: the second write fails
B's call is also , but the location is now . The test is , which is false. The location stays at and the operation returns false.
Step 4 in symbols: the retry succeeds
B reads again and gets , so it computes and calls . The test holds, so .
In general, if is the value after successful operations, each successful increment sets . Failed attempts do not change the counter at all.
A useful fact follows from the test. Suppose threads all read the same value and each calls , one after another. The first call passes and sets . Every later call tests , which is false. So exactly one of the calls succeeds, and threads must read again.
Worked examples
The counter starts at 0. Thread A calls , and then thread B calls with the value 0 it read earlier.
- A's call tests . The counter holds 0, so the test passes. The counter becomes 1 and the call returns true.
- B's call tests . The counter holds 1, so the test fails. The counter stays at 1 and the call returns false.
- B's write of 5 was never applied, so the counter is 1.
Interpretation: B's expected value was out of date. The rejected write is the mechanism that protects the counter from a stale update.
Four threads each read the counter, which holds 5, and each tries to add 1 with CAS. Assume that the losers of each round all read again before the next round starts.
- Round 1: four calls to . The first succeeds, so . Three calls fail.
- Round 2: the three losers read 6 and call . One succeeds, so . Two calls fail.
- Round 3: the two losers read 7 and call . One succeeds, so . One call fails.
- Round 4: the last loser reads 8 and calls . It succeeds, so .
- Count the calls. There are calls in total. Four succeed and fail.
Interpretation: four increments give 9, which is correct. The price of the lock-free approach is the six wasted calls. With more threads and more contention, the wasted work grows.
A bank balance holds 100 dollars. Thread W withdraws 30 dollars and thread D deposits 50 dollars. Both read 100 first. The update in each thread is to read the balance, compute the new balance, and write it with CAS.
- D calls . The balance is 100, so the write goes through and the balance is 150.
- W calls . The balance is now 150, not 100, so the call fails and nothing is written.
- W reads again and gets 150. It computes .
- W calls . The balance is 150, so the call succeeds and the balance is 120.
- Check: , which is the correct final balance.
Interpretation: a plain store would have written 70 in step 2 and erased the deposit. CAS made the withdrawal notice the deposit and redo its arithmetic from the new value.
Try it: the balance is 100. Thread A deposits 20 dollars and thread B withdraws 50 dollars, and both read 100. A's CAS succeeds first, so the balance becomes 120. B's CAS fails, B reads 120 and computes 70, and its second CAS succeeds. What is the final balance? Answer: 70, because .
Common mistakes and tradeoffs
It is tempting to think CAS makes a whole update atomic; in fact it makes one location atomic. The instruction compares and writes a single word. An update that changes two fields, such as moving an item from one list to another, needs more than one CAS, and another thread can run between them. Such updates usually need a lock or a design where the whole record is replaced by one CAS on a pointer to it.
It is tempting to think a successful CAS means nothing changed since the read; in fact only the value matches. If the value goes from A to B and back to A, a CAS expecting A succeeds even though the data changed. This is the ABA problem. For example, a stack has a top node X, and each node stores a Pointer to the next one. Thread T reads the top as X and its next node as Y, then stalls. Other threads pop X, pop Y, and push a node back at the same address as X. T's CAS that expects X and writes Y succeeds, and the stack now points to Y, which was already removed. The usual fixes are a version counter stored next to the pointer, so that a changed history never looks the same, or special memory-reclamation schemes such as hazard pointers.
It is tempting to think lock-free means fast; in fact a retry loop wastes work under contention. When many threads hit the same location, most calls fail, as Example 2 showed. A CAS-based design is lock-free, meaning that some thread always makes progress, but it is not automatically wait-free, meaning that a particular thread may keep losing and never finish. Wait-Free Synchronization is the stronger guarantee.
When to use it. Use CAS for counters, flags and single pointers, where one word captures the whole state. When not to use it. Avoid it when an invariant spans several fields, or when the update is expensive enough that many failed retries would waste more time than a lock. Alternatives. A lock is simpler and safer for multi-step updates. Message passing lets one thread own the data. Replacing a whole immutable record with one CAS on its pointer never leaves a half-updated value visible, although the ABA issue still applies when addresses are reused.
History
Before the 1970s, programmers protected shared data with interrupt masking or with software locks built from plain reads and writes. IBM's System/370 line, introduced in 1970, included a compare-and-swap instruction so that programs could update shared data without first disabling interrupts. For years it was mostly a tool for operating-system and database programmers.
Interest in lock-free programming grew as multiprocessor machines became common. A thread that holds a lock can be paused by the operating system, and every other thread then waits. In 1991 Maurice Herlihy showed that CAS can let any number of threads agree on a value without waiting, while simpler primitives such as plain reads and writes cannot do this for more than two threads. That result is one reason CAS became the standard building block for lock-free designs.
Recap
- A race happens when two threads read shared data and then write, so one write overwrites the other's update.
- CAS checks that a location still holds the expected value and writes the new value in one indivisible step.
- A failed CAS means another thread changed the value first; the thread reads again and retries.
- The retry loop never waits, so some thread always succeeds, but a given thread can keep losing.
- Watch for the ABA problem and for updates that touch more than one location.
Next, read Wait-Free Synchronization to see the strongest progress guarantee, and Linearizability for the correctness rule these objects must meet.