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 value | Expected value | New value | Result |
|---|---|---|---|
| 42 | 42 | 43 | Success, location becomes 43 |
| 44 | 42 | 43 | Failure, location stays 44 |
| null | null | pointer to node | Success, node is published |
| pointer A | pointer B | pointer C | Failure, caller rereads pointer A |
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 platform | CAS primitive | Notes |
|---|---|---|
| C11 and C++11 | atomic_compare_exchange_strong and _weak | Explicit memory order arguments |
| Java | AtomicInteger.compareAndSet, VarHandle | Volatile semantics by default |
| C# and .NET | Interlocked.CompareExchange | Full fence on all platforms |
| Go | atomic.CompareAndSwapInt64 | Sequentially consistent |
| Rust | compare_exchange, compare_exchange_weak | Separate success and failure orderings |
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.
| Primitive | Blocking | Typical use | Main weakness |
|---|---|---|---|
| Compare-and-swap | No | Lock-free updates of one word | Retries and ABA problem |
| Fetch-and-add | No | Counters, ticket numbers | Supports only arithmetic updates |
| Atomic exchange | No | Simple flags, test-and-set locks | Cannot condition on old value |
| Mutex | Yes | Multi-step critical sections | Context switches, deadlock risk |
| Read-write lock | Yes | Read-heavy shared data | Writer starvation possible |
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.
| Pitfall | Effect | Mitigation |
|---|---|---|
| ABA problem | Stale pointer accepted as current | Version tags, double-width CAS, hazard pointers |
| High contention | Many failed retries waste CPU | Exponential backoff, sharded counters |
| Weak memory ordering | Other data seen out of order | Acquire and release semantics |
| Unsafe memory reclamation | Use-after-free in lock-free lists | Epoch-based reclamation, garbage collection |
| Multi-word updates | One CAS covers only one location | Redesign state, use software transactional memory |
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.