Compare-and-Swap Operations in Concurrent Systems
How CAS guarantees atomicity but leaves room for subtle bugs.

Compare-and-swap operations make thread-safe coordination possible without locks by joining comparison and mutation in one indivisible hardware operation. That guarantee is powerful but narrow. Writing correct lock-free code takes an understanding of what CAS proves, what it cannot detect, and how contention changes its cost. The same reasoning applies to merge queues, where validation must stay tied to shared-state updates as more contributions come in.
Why thread-safe coordination without locks requires an indivisible operation
Two threads read the same counter and each computes its next value. The first thread writes its result, then the second writes the identical result over it. One increment has disappeared from the final count. Each thread performed a valid calculation, but neither protected the interval between reading the counter and writing it back.
Checking the value again before writing does not solve the problem if the check and write remain separate operations. Another thread can change the value after that extra check. This is the check-then-act race, in which a decision rests on state that may no longer exist when the program acts. Traditional synchronization closes the gap by serializing access to a critical section. Only one thread may perform the protected work at a time.
Lock-free coordination needs a different way to close that gap. The update must depend on a comparison that cannot be separated from the write. Compare-and-swap, or CAS, provides that indivisible operation, allowing a thread to attempt an update without first excluding every other participant. If the stored value no longer matches the thread’s expectation, the operation fails without changing it. The thread can then calculate a new result from the current state while preserving another thread’s work.
What CAS does at the hardware level and why atomicity holds
CAS takes three arguments, which are a memory location, an expected value, and a new value. It compares the stored value with the expectation and writes the replacement only when they match. Otherwise, it leaves memory as it was and reports failure. Its pseudocode is CAS(location, expected, new) = atomic { if *location == expected then { *location = new; return success; } else { return failure; } }. The entire conditional operation is indivisible, so another thread cannot slip an update between the comparison and the successful write.
The hardware supplies that guarantee across processor cores. On x86/x64, the instruction is CMPXCHG, while ARMv7 uses an LDREX/STREX pair and AArch64/ARMv8+ uses LDXR/STXR. Cache-coherence protocols, including MESI and variants such as Intel’s MESIF and AMD/ARM’s MOESI, coordinate access to the relevant cache line. With exclusive access, the other cores must invalidate their copies before the update can finish. This cache-line coordination uses hardware protocols independently of an OS-level lock or system call.
An algorithm usually places CAS inside a retry loop. It reads the current value, computes the desired replacement, and attempts the conditional update. If that fails, it goes back to read and calculate again. Such a loop can provide lock-free progress without guaranteeing that every participating thread finishes within a bounded number of steps. Wait-free progress requires that bound for every thread.
Maurice Herlihy’s 1991 result establishes the primitive’s broader theoretical power. CAS has infinite consensus number, compared with 1 for atomic read/write and 2 for fetch-and-add. In an n-process system, consensus objects of level ≥ n can support wait-free implementations of any concurrent object. That universality does not make an ordinary CAS retry loop wait-free.
The real performance difference between CAS and mutex-based locking
A successful CAS typically costs a handful of CPU cycles, while an uncontended mutex typically costs tens of nanoseconds. Hardware varies, so these are not universal benchmark results. The more consequential difference appears when threads compete. A failed CAS returns immediately, allowing the thread to retry or back off, whereas a blocked mutex waiter hands control to the OS scheduler. Context switches can consume microseconds or milliseconds even when the protected calculation is trivial.
With moderate contention, staying off that scheduling path can keep throughput up as the number of threads grows. CAS does not make competition disappear, however. Each failure uses processor time, and under extreme contention, optimistic updates can fail over and over. Exponential backoff addresses this by waiting briefly before retrying. In multiprocessor systems where many threads try to update the same variable, that pause delays one operation but can help the whole system run faster.
The difference also affects progress when a participant stops. A thread that crashes or loops while holding a mutex can indefinitely block every thread waiting for it. A lock-free CAS algorithm has no such lock holder. A stopped thread ceases to participate, leaving other threads able to continue. This is a progress property, distinct from the latency of one successful update.
Production systems use CAS selectively rather than treating it as a replacement for all synchronization. Java’s ConcurrentHashMap uses it for lock-free insertion into empty buckets and fine-grained synchronization for writes to occupied buckets. The Linux kernel uses CAS for atomic reference counting and in the fast path of queued spinlocks. Go’s runtime combines CAS-based lock-free local run queues with a mutex-protected global run queue. These designs place the primitive where its costs and guarantees fit the operation.
Where CAS breaks down: the ABA problem and what it actually costs
In a lock-free stack, thread T1 can read a head pointer with value A and pause before attempting its update. Thread T2 then pops that node, and the node may be freed and reallocated at the same address. When T1 resumes, the head pointer can again contain A even though it refers to recycled memory. The comparison succeeds, but T1’s understanding of the structure is stale.
In the general ABA sequence, T1 reads A, T2 changes the value to B and then back to A, and T1’s later CAS accepts the match. CAS bases its comparison on the values present at the time of the operation. It therefore cannot distinguish an unchanged location from one that changed and returned to the expected value. Unlike contention, which causes failed attempts and wasted work, ABA can allow an invalid operation to succeed.
Versioning adds the missing history to the comparison. Pairing a pointer with an incrementing counter lets CAS reject an update even when the address has returned to A, because the counter has advanced. Java’s AtomicStampedReference<T> bundles a reference with an integer stamp for this purpose. A double-length implementation on a 32-bit system can use a 64-bit CAS, with one half holding the pointer and the other the counter. With a finite counter, this makes recurrence of the combined value astronomically unlikely.
Safe memory reclamation addresses the recycled-memory source of the hazard. Hazard pointers and epoch-based reclamation protect against unsafe freeing and reuse, rather than relying only on a value comparison to establish safety. On ARM and RISC platforms, LL/SC offers another way to handle this in hardware. Its store-conditional fails if a write has touched the location since the load-link, even if the value has changed back. Authors of lock-free data structures must therefore take the architecture into account when choosing between CAS with versioning and LL/SC.
The word-size limit and multi-word state
Single-word CAS provides an atomic update within one supported word, a boundary that becomes visible as soon as an invariant spans more state than one supported atomic operation can cover. Several individually atomic writes do not become one atomic transition merely because they occur in sequence. Other threads can see the state between those writes. A design that needs a combined transition therefore requires more machinery than an ordinary CAS loop.
For application developers, the most deceptive consequence is a hidden mutex. Placing a large struct inside std::atomic can compile without error even when the CPU cannot swap that many bytes atomically. The standard library can then supply the atomic behavior through a mutex. The code remains atomic, but it is blocking. An atomic type alone does not establish that the implementation is lock-free.
Double-width CAS, or DWCAS, extends the hardware-supported span to two adjacent pointer-sized locations. The x86 instruction CMPXCHG16B is an example commonly available on consumer and server hardware. This differs from DCAS, which targets two non-contiguous locations. As of 2025, no widespread production CPUs natively support DCAS. Motorola included it in a processor line, but slowness relative to other primitives, attributed to cache handling, led to its avoidance in practice.
Direct constructions need at least three CAS operations for each word they change and may also need costly atomic instructions when they read. Transactional-memory approaches add costs for instrumented access and may offer no guarantee of non-blocking progress. Brown, Ellen, and Ruppert’s 2013 LLX/SCX approach is more restrictive than full MCAS, but enabled a concurrent binary search tree implementation that slightly outperformed a JDK CAS-based skip list. IBM POWER8 and Intel TSX provide hardware transactional memory, although TSX’s history includes correctness errata and selective disablement.
How CAS logic scales up: merge queues as distributed compare-and-swap
A merge queue applies the same conditional-update logic to a repository. The expected state is the branch state against which a proposed change was validated, and the update is the merge into the shared branch. Before proceeding, the queue must establish that the validation still applies to the current branch tip. If the relevant state has changed, the proposal must be rebased and re-validated. This is distributed compare-and-swap as an architectural analogy.
The race is concrete when two changes interact. Person A removes a function while Person B adds a call site for it. Both pull requests can pass CI on their own against their original base, yet break the main branch if they are merged without serialization and validation of the combined state. An unchecked interval between validation and merge recreates the check-then-act gap.
GitLab’s merge trains extend validation across the ordered set of pending changes. Each merge request is tested against the combined changes of every request ahead of it. This catches conflicts that isolated PR testing would miss. The queue thus coordinates both the order of updates and the state against which their validity is assessed. Serialization alone would not establish that an earlier test result remains applicable.
The cost to throughput is like that of contention in a CAS loop. A 2026 production case at cfg-is/cfgms found that one queue entry fanned out approximately 42 non-skipped CI jobs across 9 workflows. Five concurrent speculative groups produced approximately 200 concurrent hosted-job demand, far beyond the account concurrency cap. Throughput degraded to roughly 5 merges per 3 hours. Re-queuing consumed resources without producing commits, demonstrating how optimistic work can overwhelm the capacity needed to complete it.
Why agent-scale PR volume makes merge-queue correctness a first-order concern
AI coding agents move PR submission from human-paced work toward machine-paced volume. Stripe’s production deployment of “minions,” AI coding agents launched from Slack reactions, ships roughly 1,300 PRs weekly. That volume increases the opportunities for changes to invalidate one another between testing and merging. It also raises the cost of a broken shared branch. Every agent depending on that branch can be blocked alongside the humans waiting for a repair.
At this scale, testing after merge and reverting on failure creates a feedback loop that is too slow. The architectural response is to move validation before the shared-state update through pre-merge CI in the queue. The tested state must remain the state authorized for merging. Otherwise, pre-merge testing just moves the check earlier and leaves the race open.
Agents can also be allowed to use queue validation without being allowed to trigger the actual merge. They can run the test suite against a speculative merged state and establish whether their changes are clean before committing them to the shared branch.
A queue configured for human-speed throughput, with small concurrency limits and no batching, can become the bottleneck when agents supply most contributions. Infrastructure for agentic software factories therefore needs to be composable, tunable for the actual contention regime, and observable enough to expose queue saturation. The governing discipline remains precise conditional mutation. At both the memory location and the shared branch, an update is safe only when the state that justified it still supports it.


