Compare-and-swap

Also known as: CAS

On this page 7

Compare-and-swap (CAS) is an atomic operation that reads a memory location, compares it with an expected value, and writes a new value only if the two match, all as one indivisible step. In concurrency and programming generally, CAS is the fundamental building block of lock-free data structures, atomic counters and many mutex implementations, because it lets a thread detect and react to interference from other threads without blocking.

The operation returns either a success flag or the value it actually found, so the caller knows whether the update took effect. If another thread changed the location first, the CAS fails and the caller typically rereads the value and retries.

How compare-and-swap works

A CAS takes three operands: a memory address, the expected old value and the desired new value. The processor guarantees that no other write to that address can occur between the comparison and the store, so the whole read-compare-write sequence behaves as a single atomic step from the point of view of every other core.

Typical usage follows a read-modify-CAS loop. A thread loads the current value, computes a new value from it, and attempts a CAS from the loaded value to the computed one. If the CAS fails, the thread reloads and tries again. This pattern is called optimistic concurrency because it assumes conflicts are rare and pays a retry cost only when they happen.

The following table shows how the operands determine the outcome of a single CAS call.

Current valueExpected valueNew valueResult
424243Success, location becomes 43
444243Failure, location stays 44
nullnullpointer to nodeSuccess, node is published
pointer Apointer Bpointer CFailure, caller rereads pointer A
Outcome of a compare-and-swap call

Hardware and language support for CAS

Modern processors expose CAS either as a dedicated instruction or as a pair of instructions that together provide the same guarantee. On x86, LOCK CMPXCHG performs a full CAS and acts as a full memory barrier. ARM and RISC-V historically use load-linked and store-conditional (LL/SC), where the store fails if the location was written after the load; ARMv8.1 also added a direct CAS instruction.

High-level languages wrap these instructions in portable atomic APIs, which also control memory ordering. Choosing the correct ordering is part of using CAS correctly, because the atomic update alone does not order surrounding reads and writes.

Language or platformCAS primitiveNotes
C11 and C++11atomic_compare_exchange_strong and _weakExplicit memory order arguments
JavaAtomicInteger.compareAndSet, VarHandleVolatile semantics by default
C# and .NETInterlocked.CompareExchangeFull fence on all platforms
Goatomic.CompareAndSwapInt64Sequentially consistent
Rustcompare_exchange, compare_exchange_weakSeparate success and failure orderings
CAS primitives in common languages

The weak variant may fail spuriously even when the values match, which reflects LL/SC hardware behavior. Inside a retry loop the weak form is usually faster, while a single standalone attempt should use the strong variant.

Compare-and-swap compared with other synchronization tools

CAS sits at a lower level than locks and semaphores and is often used to implement them. A spinlock is commonly a CAS loop on a flag, and many mutexes use a CAS on the fast path before falling back to an operating-system wait queue. The key difference is that CAS never blocks the calling thread, whereas a lock can suspend it.

PrimitiveBlockingTypical useMain weakness
Compare-and-swapNoLock-free updates of one wordRetries and ABA problem
Fetch-and-addNoCounters, ticket numbersSupports only arithmetic updates
Atomic exchangeNoSimple flags, test-and-set locksCannot condition on old value
MutexYesMulti-step critical sectionsContext switches, deadlock risk
Read-write lockYesRead-heavy shared dataWriter starvation possible
CAS versus related primitives

Because CAS is universal for consensus, any wait-free or lock-free algorithm for a shared object can in principle be built from it, a result that simpler primitives such as test-and-set cannot match.

The ABA problem and other pitfalls

The best-known hazard is the ABA problem. A thread reads value A, is preempted, and meanwhile another thread changes the location to B and back to A. The first thread’s CAS then succeeds even though the underlying state changed, which can corrupt lock-free stacks and queues when a node was freed and reused at the same address.

Several mitigations exist, and the right one depends on the data structure and runtime.

PitfallEffectMitigation
ABA problemStale pointer accepted as currentVersion tags, double-width CAS, hazard pointers
High contentionMany failed retries waste CPUExponential backoff, sharded counters
Weak memory orderingOther data seen out of orderAcquire and release semantics
Unsafe memory reclamationUse-after-free in lock-free listsEpoch-based reclamation, garbage collection
Multi-word updatesOne CAS covers only one locationRedesign state, use software transactional memory
CAS pitfalls and common mitigations

Under heavy contention, a naive CAS loop can perform worse than a well-implemented mutex, because cache lines bounce between cores and most attempts fail. Lock-free code also offers only progress guarantees for the system, not fairness for individual threads, so resource starvation remains possible.

When to use compare-and-swap

CAS is most valuable when the shared state fits in a single machine word and contention is moderate. Typical cases include reference counts, sequence numbers, lazy initialization, publishing a pointer to a fully built object, and the head pointer of a lock-free stack.

  • Prefer library structures such as concurrent queues and atomic counters over hand-written CAS loops.
  • Use a mutex when an update spans several fields or must call blocking code.
  • Measure under realistic contention, since lock-free code is not automatically faster.
  • Test with stress tools and model checkers, because CAS bugs often appear only under rare interleavings.

Explained without jargon

Compare-and-swap is a way for a program to say: change this value only if it is unchanged since it was last read. If someone else changed it in the meantime, nothing happens and the program tries again with the fresh value.

Imagine editing a shared spreadsheet cell. Before saving, the software checks whether the cell still holds the number you started from. If a colleague already changed it, your save is refused instead of silently overwriting their work, and you redo your change on top of theirs.

A typical use case

A web service handles about 50,000 requests per second across 32 worker threads and must assign each request a unique, increasing ID. An early version protected the counter with a mutex, and profiling showed threads spending noticeable time waiting on that lock during traffic peaks.

The team replaces the mutex with an atomic 64-bit counter updated through a CAS loop, and later with fetch-and-add, which the hardware implements even more efficiently for simple increments. For a separate cache structure, they use CAS to publish a fully built configuration object by swapping a single pointer, so readers never see a half-updated configuration. Lock waits disappear from the profile, and tail latency during peaks drops measurably.