CAS & Atomic Classes: Spin Optimism vs Blocking Pessimism
This article analyzes CAS and Java atomic classes through three production incidents, covering hardware-level lock cmpxchg, spin-loop internals, ABA problems, LongAdder's segmented counting, AtomicStampedReference, field updaters, and a seven-point checklist for safe CAS usage, with source code walkthroughs and interview Q&A.
Reading font

Three Production Incidents
The article opens with three real-world accidents that illustrate the boundaries of CAS and atomic classes:
Accident 1: High-Contention Spin Storm
A flash-sale service used AtomicLong.incrementAndGet for inventory pre-check counting. Under 1000 concurrent threads, CPU hit 100% while throughput dropped. The cause: incrementAndGet uses a do-while spin CAS loop. With 1000 threads contending on the same memory address, every CAS failure triggers an immediate re-read, re-compute, and retry. The cache line ping-pongs between cores, and useful computation falls below 20%. The fix: replace with LongAdder (internal segmented Cell array), which reduced CPU to under 25% and tripled throughput. Lesson: "lock-free is faster" only holds under low contention; high contention makes spin the most expensive wait.
Accident 2: ABA Due to Object Reuse
A payment gateway used AtomicReference<ChannelState> with objects from a pool. Thread 1 reads state A (healthy), gets descheduled. Thread 2 changes state to B (circuit-break) then back to A (recovery) — the pool returns the same object. Thread 1 resumes, CAS expects A and succeeds, but the channel has undergone a full circuit-break cycle. Subsequent retries hit the broken channel, causing 120k loss. Fix: add a version stamp via AtomicStampedReference, comparing both reference and stamp. Lesson: bare CAS is unsafe whenever objects are reused or values can revert.
Accident 3: Check-Then-Act Race
A coupon service used if (atomic.get() > 0) atomic.set(atomic.get() - 1). Two threads both read 1, both pass the check, both set to 0 — two redemptions only decrement once, over-issuing 4000 coupons. Cause: get and set are two independent atomic operations; the check and compute between them are unprotected. Fix: use decrementAndGet (internal CAS loop fuses read-compute-write) or getAndUpdate functional API. Lesson: individual atomic methods are atomic, but a read-then-write combination never is — use composite APIs or write your own CAS loop.
1. Why CAS: The Cost of Locks
A synchronized lock/unlock with no contention is cheap (biased/lightweight lock), but under contention it forces "park - kernel schedule - unpark", a microsecond context switch. If the critical section is just "increment an int" (nanoseconds), lock overhead is 1000x the work. Optimistic strategy: don't lock, just modify; compare old value before swap, retry if someone else won. That compare-and-swap is CAS. Its premise: conflicts are rare. Most attempts succeed on first try, avoiding locks entirely; failures pay retry cost. Thus CAS benefit correlates strongly with conflict rate.
CAS semantics in three sentences: Input — memory address V, expected old value E, new value N. Action — if (V == E) then V = N, atomically. Return — V's old value (or boolean success). It atomizes read-compute-write sequences, e.g., counter getAndAdd: read old, compute old+1, CAS(old, old+1). If another thread changed the value, CAS fails, re-read and retry. The whole loop has no lock, using "fail and retry" to achieve mutex-equivalent exclusion — this is optimistic concurrency.
Optimistic vs Pessimistic Comparison: Pessimistic (lock) = acquire mutex then operate; stable under high contention but park/unpark costly. Optimistic (CAS) = operate directly, retry on conflict; zero wait when conflicts rare, but spins burn CPU when frequent. Deciding factor is conflict rate: read-heavy, writers staggered (CHM buckets), low-contention counters → optimistic. Writers highly concentrated (global counter at 1000 threads), critical section contains I/O → pessimistic. CHM is a hybrid exemplar: empty buckets low conflict → CAS; non-empty buckets high conflict → synchronized.
2. CAS Hardware Foundation: One CPU Instruction
CAS atomicity is guaranteed by CPU, not Java. On x86 it maps to lock cmpxchg — cmpxchg does compare-exchange, lock prefix makes it "bus/cache-line level indivisible". The lock prefix does two things: locks the cache line (modern CPUs lock the cache line holding the address, other cores must wait) + full barrier (forbids reordering, flushes write buffers). So one CAS = atomicity + visibility + ordering all in one — it adds a "compare" semantic over volatile write at nearly same cost (one lock operation, tens of nanoseconds).
Two Java call chains invoke this instruction:
Unsafe class — compareAndSwapInt/Long/Object native methods, direct mapping to lock cmpxchg. JDK internals (atomic classes, AQS, CHM) all use it. Since Java 9, application code is restricted (modularization makes reflective Unsafe access harder).
VarHandle — standard replacement from Java 9 via MethodHandles.lookup. Supports plain/opaque/acquire-release access modes and fence barriers; type-safe equivalent of Unsafe.
Discipline for business code: Use atomic classes ( Atomic*) for 95% of cases; need field-level or array-level fine control → VarHandle; never depend directly on Unsafe — it's not public API and may break on JDK upgrade.
Three Boundaries of CAS (High-Frequency in Interviews and Practice): 1) Single variable — CAS protects one word per operation; multi-variable invariants (e.g., "amount -a, inventory +b") cannot be expressed, need lock or encapsulate as single object replacement. 2) ABA — compares value not history; detailed in section 4. 3) Spin cost — unbounded retries, high contention burns CPU; solutions: LongAdder (section 4) and backoff templates (section 6). All three boundaries have tools, but you must know where they lie.
3. Spin Core: getAndAddInt Do-While Skeleton
All atomic class "read-modify-write" methods share the same skeleton. AtomicInteger.getAndAddInt in four lines:
Volatile read old value ( getIntVolatile, guarantees latest).
Compute new value locally.
CAS compare old, swap new.
Fail → continue back to step 1 re-read/re-compute.
This do-while loop is the "lock-free version of a spin lock": it doesn't block, fails and retries immediately. Low contention: loop 1-2 times, cost = one CAS (tens of ns). High contention: failures "infect" each other — each retry may cause other threads to fail; 1000 threads spinning on same address burn all CPU in the loop — the mechanism of Accident 1. Health check: average retry count (atomic classes don't expose it, but infer from pressure-test TPS vs CPU curve — TPS flat while CPU rises = spin storm).
Atomic Class Family in Four Tiers
AtomicInteger/AtomicLong/AtomicBoolean — scalar atomics; getAndAdd / compareAndSet / incrementAndGet are the three core ops.
AtomicReference<V> — object reference atomic; combined with immutable objects for "whole replacement", the standard pattern for CAS on composite state.
AtomicIntegerArray/LongArray/ReferenceArray — array element atomics; index-level CAS (ordinary volatile array elements don't guarantee atomic access, that's their raison d'être).
Atomic*FieldUpdater — field updaters; atomize volatile fields of plain classes without wrapper object overhead. Java 8 added functional APIs: updateAndGet(IntUnaryOperator), accumulateAndGet, getAndUpdate — encapsulate "write your own do-while" but retry semantics unchanged.
Field Updater Deep Dive
AtomicIntegerFieldUpdater.newUpdater(Class, String)creates an updater; field must be volatile, non-static (private allowed but visibility semantics must hold). Value in large object scenarios : 100k-node graph, each node has a state field — using AtomicInteger per node adds 16 bytes object header; field updater adds zero allocation. Cost: reflection lookup once at creation, runtime zero; strict field requirements (missing volatile → silent degradation to plain read/write — its nastiest trap: newUpdater throws if field lacks volatile, which is actually good — error front-loaded).
Optimistic vs Pessimistic Selection Checklist: Go optimistic (CAS/atomics): counting/stats (low contention or LongAdder), state toggles ( AtomicBoolean single flip), reference replacement (immutable object + AtomicReference ), bucket-level low-conflict writes (CHM pattern). Go pessimistic (locks): critical section contains I/O/remote calls, multi-variable invariants, writers highly concentrated and unsplittable (consider split first then lock), need wait/notify cooperation. Don't be dogmatic: first ask "can I shard the hotspot?" (segmentation), then ask optimistic vs pessimistic.
4. ABA and LongAdder: Two Advanced Topics
ABA Full Timeline (Accident 2 Replay)
Thread 1 reads value A, prepares CAS(A→C), gets descheduled. Thread 2 changes A to B, then back to A (or pool returns same object). Thread 1 resumes, CAS expects A — succeeds. But between the two A's lies a full state cycle; thread 1 is oblivious. CAS compares value, not history. When is ABA a real problem? Three conditions: state has history dependency (state machine progression), objects are reused or revert to old value, intermediate state has side effects (e.g., resource release). Pure incremental counting is naturally ABA-free (value monotonically changes, never returns). Lock-free stack/queue head operations are ABA hotspots — node recycled and reallocated, pointer value same but memory changed.
Solution: Version Stamps
AtomicStampedReference<V> — packages "reference + int stamp" into a Pair, CAS compares both ( casPair), stamp increments on each modification; value can return to old but stamp cannot.
AtomicMarkableReference<V> — lightweight version; stamp collapses to a boolean mark, only distinguishes "changed or not".
Don't over-apply: not every CAS needs version — incremental counters, single toggles, monotonically changing values are naturally ABA-free. Adding version has cost (extra stamp write + Pair allocation per modification); only apply when all three conditions hit: object reuse + state machine + intermediate side effects.
LongAdder: The Answer for High-Contention Counting
Core idea in one sentence: Turn "one hot variable" into "a group of cold variables" . Structure: a volatile long base + a CounterCell[] array (lazily created). Write path: CAS base succeeds → done (low contention zero overhead); CAS base fails → contention detected → divert to a Cell array index (thread's own probe value determines index, same thread likely hits same Cell, cache-friendly) and do segmented add. Read ( sum): traverse base + all Cells sum — no global snapshot, concurrent writes during traversal not included, so sum is approximate . This is the same design as CHM's CounterCell (CHM copied LongAdder directly): the hotter the spot, the more you shard; reads tolerate approximation, gaining near-zero-contention writes.
Counting Three-Way Selection (Delivering on Chapter 3 Preview): AtomicLong — low concurrency (<100 threads contending same counter) or need exact single-point read-write (rate limiter decisions depend on read-then-CAS). LongAdder — high concurrency write-mostly stats (QPS, error counts, bytes), sum tolerates approximation. LongAccumulator — generalized LongAdder, custom aggregation function (max/min/sum). volatile + lock — multi-variable linked invariants (two counters must increment/decrement together). Monitoring counters go straight to LongAdder; don't gamble on AtomicLong — that's the discipline bought by Accident 1.
5. Production Practice: Four Scenarios, Four Templates
5.1 QPS & Monitoring Counters: LongAdder (Accident 1 Fix)
private final LongAdder qps = new LongAdder();
private final LongAdder errors = new LongAdder();
// Hot path: once per request, nanoseconds
public void record(boolean ok) {
qps.increment();
if (!ok) {
errors.increment();
}
}
// Scheduled task: sample and reset every 10s
@Scheduled(fixedRate = 10_000)
public void sample() {
long v = qps.sumThenReset();
long e = errors.sumThenReset();
// Report metrics: approximate is fine
metrics.gauge("qps", v * 100.0 / 10_000);
if (e > THRESHOLD) {
breaker.open();
}
}Three key points: Hot path uses only increment — LongAdder write path is "CAS base fail → own Cell", 1000 threads each hit different Cells, no contention. Sampling uses sumThenReset not sum then manual reset — single traversal sums and resets, avoiding window where new writes between sum and reset get incorrectly cleared (though LongAdder lacks atomic sum-then-reset global consistency, single-threaded scheduler suffices). Breaker judgment tolerates approximation — threshold off by 1-2 irrelevant; don't swap back to AtomicLong for precision. Anti-pattern: don't call sum() in high-frequency loops — it's O(Cell count) traversal; monitoring panel 10s refresh is its design frequency, not your hot path frequency.
5.2 ABA Prevention: AtomicStampedReference Version Stamp (Accident 2 Fix)
private static final class Channel {
final String id;
volatile boolean healthy;
Channel(String id) { this.id = id; }
}
private final AtomicStampedReference<Channel>
cur = new AtomicStampedReference<>(null, 0);
public boolean transition(Channel expect,
Channel next) {
int[] stamp = new int[1];
// Read reference and stamp atomically
Channel c = cur.get(stamp);
if (c != expect) {
return false; // State already advanced by another
}
// CAS: both reference and stamp must match
boolean ok = cur.compareAndSet(
expect, next, stamp[0], stamp[0] + 1);
if (!ok) {
// Failed: version changed, replay state machine
return false;
}
return true;
}Three critical actions: get(stamp) atomically retrieves reference and stamp — two separate calls ( getReference + getStamp) could race, must use the int[] out-param overload. compareAndSet four-arg version — expected reference, new reference, expected stamp, new stamp; all four must match. CAS failure returns false to let state machine replay — version changed means concurrent progression, replay safer than blind spin (progression logic may no longer apply). Reiterate criteria: only when "object reuse + state machine + intermediate side effects" all three hit do you add Stamped — pure counters, toggles don't need version; each modification adds a Pair allocation, real cost. Object pool alternative: reset stamp to new value on pool return, semantically equivalent to "disallow old version reuse".
5.3 Legacy Class Retrofit: AtomicIntegerFieldUpdater Zero-Allocation Atomization
public class Node {
// Prerequisite: must be volatile, non-static
volatile int state; // 0 init 1 ready
// -1 failed
// Updater static, created once via reflection
private static final
AtomicIntegerFieldUpdater<Node> UP =
AtomicIntegerFieldUpdater.newUpdater(
Node.class, "state");
boolean markReady() {
// CAS: 0 -> 1, single flip
return UP.compareAndSet(this, 0, 1);
}
int markFail() {
// Functional: spin to set state -1
return UP.updateAndGet(this,
s -> s == 1 ? s : -1);
}
}100k-node graph/tree, each node a state field — AtomicInteger per node adds 16 bytes header, 1M nodes = 16MB extra heap; field updater zero extra allocation. Four disciplines: Field must be volatile — missing volatile throws IllegalArgumentException at newUpdater (good, error front-loaded). Updater declared static final — creation involves reflection, one global instance. Updater only works on "instances of this class" — subclass field shadowing causes silent errors (same field name trap). Visibility comes from field's own volatile, not updater — updater adds atomicity, not semantics. When not to use: few fields, small objects — plain AtomicInteger simpler and clearer; optimization needs human-readable justification (memory savings calculable).
5.4 CAS Composite Operations: Correct check-then-act (Accident 3 Fix)
// Anti-pattern (Accident 3): two non-atomic steps
// if (cnt.get() > 0) cnt.set(cnt.get() - 1);
// Fix 1: Composite API, internal spin
public boolean tryConsume() {
return cnt.getAndDecrement() > 0;
// getAndDecrement returns old value:
// old > 0 means this consumption valid
}
// Fix 2: Encapsulate state as immutable object
// + AtomicReference whole replacement
record Inventory(long count) {}
private final AtomicReference<Inv>
inv = new AtomicReference<>(new Inv(100));
public boolean tryConsume2() {
Inv cur;
Inv next;
do {
cur = inv.get();
if (cur.count() <= 0) {
return false;
}
next = new Inv(cur.count() - 1);
} while (!inv.compareAndSet(cur, next));
return true;
}Two fixes map to two complexity levels: Fix 1 — fuse "check and decrement" into one atomic method; getAndDecrement returns old value, old > 0 means this decrement valid — semantic nuance: near zero concurrent may see "return 0 but didn't actually decrement", inventory allows; if not allowed use Fix 2 . Fix 2 — encapsulate multi-field state into immutable record, CAS whole reference — this is the standard technique to break the "single variable boundary": only one variable (the reference), state can be arbitrarily complex. Do-while template three elements: get at loop head (re-read every retry), check and construct new value in loop body, CAS fail → continue. New value must be freshly constructed each retry — reusing previous next object is a subtle bug (it may have been successfully CAS-written by this or another thread). Rule of thumb: state fields > 2, or state transitions > 1 path, go straight to Fix 2 + consider version stamp (5.2).
CAS Usage Review: Seven-Point Physical (One Veto Fails): 1) High contention (many writers on same variable) still bare spinning? → LongAdder or lock (Accident 1). 2) Object reuse / value revert scenarios checked for ABA? → Stamped (Accident 2). 3) check-then-act two-step combo stuffed into CAS? → Composite API or immutable object whole replacement (Accident 3). 4) Spin loop has limit or backoff? → Retry N times then fallback to lock. 5) Complex business logic crammed into one CAS? → What CAS can't express, use lock. 6) Field updater's field volatile? Updater static final? 7) Counter chosen by concurrency level? All seven pass → atomic class cleared for production.
6. Core Source Code: Four Key Implementations
First: Unsafe.compareAndSwapInt Declaration and x86 Landing
// Unsafe.java (JDK 17, declaration)
public final native boolean
compareAndSwapInt(Object o, long offset,
int expected, int x);
// x86_64 landing (hsdis disassembly pseudo):
// mov eax, expected ; expected into register
// lock cmpxchg [o+offset], x
// ; compare [o+offset] with eax:
// ; equal -> write x, ZF=1
// ; not equal -> eax refreshed with current memory value
// ; ZF=0
// lock prefix: cache line exclusive + full barrier
// (same cost as StoreLoad in Chapter 3)Two takeaways: offset is field offset inside object — Unsafe doesn't know field names, knows offsets; objectFieldOffset computed once and passed in, that's the reflection product from field updater creation. cmpxchg failure refreshes eax with current memory value — so "CAS fail retry" doesn't need explicit reload; hardware hands back latest value for free. Atomic class source's explicit getIntVolatile in do-while is for volatile semantics generality; on x86 it's a free lunch. lock prefix cost (cache line lock + full barrier) same origin as volatile write — CAS is not a "free write", it's the most expensive single write, expensive for a reason: buys atomicity .
Second: AtomicInteger.getAndAddInt — Standard Spin Kernel
// AtomicInteger (JDK 17)
private static final Unsafe U =
Unsafe.getUnsafe();
private volatile int value;
public final int getAndAddInt(Object o,
long offset, int delta) {
int old;
do {
// volatile read: re-read every retry
old = U.getIntVolatile(o, offset);
// CAS: fail continue retry
} while (!U.compareAndSwapInt(
o, offset, old, old + delta));
return old;
}
public final int incrementAndGet() {
// 1.8 optimization: addAndGet returns new value,
// fail uses cmpxchg's returned current value
return U.getAndAddInt(this, VALUE,
1) + 1;
}Four-line loop is the series' backbone: do-while not for(;;)+break — do once then check, guarantees at least one attempt. getIntVolatile not plain get — offset path read must explicitly declare volatile semantics. old + delta computed inside CAS param — no gap for another thread to sneak in, because "read old → compute old+delta → CAS(old, old+delta)" if old stale, CAS must fail, whole sequence restarts — atomicity isn't three steps uninterrupted, it's "stale input invalidates the whole" , the essence of optimistic concurrency. Memorize this skeleton; any hand-written CAS loop (5.4 Fix 2) is a variant.
Third: LongAdder.add — Segmented Aggregation Write Path
// LongAdder / Striped64 (JDK 17 simplified)
public void add(long x) {
Cell[] as; long b, v; int m;
Cell a;
// Prefer CAS base
if ((as = cells) != null
|| !casBase(b = base, b + x)) {
boolean uncontended = true;
// cells not built -> create array
// locate cell -> CAS cell
if (as == null
|| (m = as.length - 1) < 0
|| (a = as[getProbe() & m])
== null
|| !(uncontended = a.cas(
v = a.value, v + x))) {
// Fallback: expand cells / retry
longAccumulate(x, null,
uncontended);
}
}
}
public long sum() {
long sum = base;
Cell[] as = cells;
if (as != null) {
for (Cell a : as) {
if (a != null) sum += a.value;
}
}
return sum; // lock-free snapshot, approximate
}Four-layer funnel: 1) CAS base — no contention one-step. 2) Cells not built and CAS base fails — longAccumulate creates Cell array (initial 2, doubles up to CPU core limit). 3) Locate Cell CAS — getProbe() (thread probe) & (len-1) picks Cell, hit own Cell → segmented add. 4) Cell CAS also fails — longAccumulate changes probe to relocate or expands cells retry. sum is pure read traversal no lock — this is the "write fast read slow" trade-off: sum's O(n) buys increment's O(1) zero contention . Compare with Chapter 6 CHM's CounterCell: addCount structure identical — CHM copied LongAdder unapologetically (same author Doug Lea). Understand this segment, Chapter 6's counting source auto-clarifies.
Fourth: AtomicStampedReference.casPair — Version Stamp CAS Implementation
// AtomicStampedReference (JDK 17)
private static class Pair<T> {
final T reference;
final int stamp;
// reference and stamp packaged, immutable
}
private volatile Pair<T> pair;
public boolean compareAndSet(
T expectedReference,
T newReference,
int expectedStamp,
int newStamp) {
Pair<T> current = pair;
return
expectedReference == current.reference
&& expectedStamp == current.stamp
&& ((newReference == current.reference
&& newStamp == current.stamp)
|| casPair(current,
Pair.of(newReference,
newStamp)));
}
private boolean casPair(Pair<T> cmp,
Pair<T> val) {
// Still single-variable CAS underneath:
// CAS pair reference
return U.compareAndSwapReference(
this, PAIR, cmp, val);
}Most interesting point: "Double-variable CAS" ultimately remains single-variable CAS — package reference and stamp into an immutable Pair object, CAS the pair reference once. This is the textbook demo of "encapsulation breaks single-variable boundary": two logical variables merge into one physical variable, one CAS solves it. The short-circuit expression also has nuance: if expected equals current exactly, return true without CAS (saves one lock op); reference equal but stamp different must go through casPair (stamp changed means changed). This pattern copies directly into your own code: any "multi-field linked check", package immutable object + AtomicReference, that's your Stamped — unified theoretical basis for 5.2 and 5.4 Fix 2.
7. Seven Accounts: CAS Selection and Cost
Account 1: Contention Rate. CAS benefit correlates with conflict rate — below 20% conflict, CAS lock-free crushes locks; above 50%, spin burn exceeds lock's queue cost. Conflict rate is first input; if unmeasurable, pressure test: TPS flat CPU rising = spin storm — this account decides optimistic vs pessimistic fundamental direction.
Account 2: ABA. Bare CAS compares value not history — object reuse, state machine, intermediate side effects: hit one condition, one loss accident pays ten years of version stamp premium. StampedReference's Pair allocation is the priced insurance; Accident 2's 120k loss is the bill for unpaid premium .
Account 3: Segmentation. LongAdder turns one hotspot into Cell array — write contention zeroed, cost: sum becomes O(n) approximate read. Monitoring counters, stats accumulation — "write 100k times read once" — this account wins; "every write must read" rate limiter — this account loses in reverse — read-heavy exact scenarios stay in AtomicLong.
Account 4: Wrapper Object. AtomicInteger each instance adds 16 bytes header — singleton counter irrelevant, million-node collection = tens of MB. Field updater is zero-allocation alternative, but requires volatile field and global singleton updater — this account only pays off in large object structures, don't add reflection for three fields .
Account 5: Complexity. CAS loop trades "mutex" for "retry" — retry path correctness (re-read, re-compute, re-construct new value) is your burden; 5.4's "next must not be reused" is the retry path's subtle bug. Lock code easy to write hard to test; CAS code hard to write hard to test — high business complexity, lock's maintainability wins on paper .
Account 6: Visibility Free-Ride. lock prefix includes full barrier — one CAS = atomicity + volatile write visibility free. State maintained via CAS naturally visible to other threads, no extra volatile needed — AQS's state one field solves both mutex and visibility (Chapter 4), the best exemplar of this account .
Account 7: Ecosystem. AQS state CAS, thread pool ctl, CHM empty bucket, LongAdder, FutureTask state — JUC's skeleton moves are all CAS. Master this chapter, all previous "CAS here" annotations cash out, next Chapter 8 CompletableFuture state machine likewise CAS-driven . Seven accounts summary: CAS direct cost near zero (low contention), all risk from out-of-bounds use — it's the fastest sync primitive, also the one with clearest boundaries: single variable, value compare, unbounded retry; three boundaries each have a matching umbrella.
8. 20 Interview Questions (with Answers)
The article includes 20 detailed Q&A covering CAS definition, x86 instruction, Unsafe vs VarHandle, getAndAddInt principle, high-concurrency AtomicLong problem and LongAdder fix, ABA definition and scenarios, AtomicStampedReference mechanism, AtomicMarkableReference difference, atomic classes vs locks boundaries, AtomicIntegerFieldUpdater purpose and disciplines, volatile array element atomicity, LongAdder sum precision, compareAndSet vs weakCompareAndSet, getAndIncrement vs incrementAndGet return values, LongAccumulator, CAS loop new object reuse, lock-free vs lock performance, CHM CounterCell vs LongAdder, Thread.onSpinWait, and lock/CAS/LongAdder selection decision chain.
One-Page Cheat Sheet
CAS Foundation & Spin: CAS = if V==E then V=N; hardware = lock cmpxchg (cache line lock + full barrier, same origin as volatile write); Java chain Unsafe → VarHandle, business uses atomics; spin kernel do-while: volatile read → local compute → CAS → fail retry; atomicity essence = "stale input invalidates whole"; low conflict 10x faster, high conflict spins burn CPU — conflict rate is first input.
ABA & Segmentation: ABA = value same but world changed two rounds; three conditions hit then version stamp (object reuse + state machine + intermediate side effects); StampedReference = reference+stamp packaged Pair, underneath still single-variable CAS — general solution for multi-field linkage; LongAdder = base+Cell[] four-layer funnel (CAS base → build cells → probe locate → fallback expand), sum approximate; CHM CounterCell same design.
Selection & Physical: Counting three-way: high concurrency stats LongAdder, low concurrency exact AtomicLong, multi-variable linked lock; check-then-act use composite API (getAndDecrement returns old to judge) or immutable object + AtomicReference whole replacement; seven-point physical: bare spin, ABA, two-step into CAS, spin limit, complex logic, field volatile, Adder selection; CAS loop retry new value must be freshly constructed.
This article starts from three accidents, walks CAS from CPU instruction to production selection: lock cmpxchg's cache line lock gives atomicity, do-while spin gives retry semantics, and the "only fast under low conflict" boundary gives selection discipline — low conflict go optimistic (atomics), hotspot concentrated then shard (LongAdder), complex state package replace (AtomicReference + immutable object), history-sensitive add version (Stamped). Production solutions converge to two checklists: three-way selection (counting scenarios) and seven-point physical (all CAS code), plus do-while loop three elements (get at loop head, judge in loop body, new value freshly constructed). CAS's ledger matches its reputation: fast is truly fast, boundaries are truly hard — those who treat boundaries as design inputs write lock-free high performance; those who treat boundaries as background noise manufacture loss accidents .
For questions about attribution, corrections or content rights, please contactand we will review it promptly.