NOTE

6.4 Compare-and-Set (CAS)

Atomic compare-and-set as a read-modify-write primitive, retry loops, contention, ABA, and when lock-free does not mean contention-free.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. CAS

Compare-and-set atomically performs the conceptual operation:

if current == expected:
    current = update
    success
else:
    fail

The compare and update form one atomic read-modify-write operation.

2. Retry Loop

CAS is often used in a loop:

for (;;) {
    int old = value.get();
    int next = old + 1;
    if (value.compareAndSet(old, next)) break;
}

Under contention, failed threads retry instead of blocking on a mutex.

3. Lock-Free Is Not Free

CAS avoids lock ownership/blocking in many algorithms, but heavy contention can cause repeated failed retries and cache-line bouncing.

A lock can outperform CAS under some workloads.

4. ABA

If a value changes A → B → A, a CAS that only compares the final value cannot tell that an intervening change occurred.

Solutions include version/stamp fields (AtomicStampedReference), immutable nodes, or algorithm-specific reclamation/versioning.

5. Java APIs

Modern Java exposes atomics through java.util.concurrent.atomic and lower-level VarHandle APIs. The JVM maps operations to target-specific atomic instructions and memory-ordering semantics.

Loading helpful count