Java Materials
← Core Java · Chapter 14

Atomics and lock-free progress

CAS updates only if the observed value still matches the expected one. Competing writers can force retries. ABA means a value changed away and came back between the initial read and CAS, which matters when the history carries meaning. AtomicStampedReference can include a version; AtomicMarkableReference includes a Boolean marker.

CAS retries and safe update functions

Definition:

CAS writes a replacement only when the current value matches the expected value.

Explanation:

A CAS loop needs a pure or retry-tolerant transform.

Illustration image:

Writer B changes the shared value first. Writer A’s stale expected value no longer matches, so it must read the current value and compute a new candidate. Two writers contend for one valueWriter AWriter Breads 4CAS 4→5 failsretryCAS 4→5 succeedsShared state now contains 5
Writer B changes the shared value first. Writer A’s stale expected value no longer matches, so it must read the current value and compute a new candidate.

Example:

Worked Java example · see surrounding context in notes
var state = new java.util.concurrent.atomic.AtomicInteger(0);
int committed = state.updateAndGet(previous -> Math.addExact(previous, 1));
System.out.println(committed);

Expected behavior. Prints 1 for this run. The update function may run more than once in a contended application.

Internal working:

AtomicReference.updateAndGet can call the supplied function multiple times when updates contend. Do not send messages, charge payments or write logs that must occur once from the transform. If recording a durable effect with state, use a transactional boundary and an outbox rather than assuming CAS protects both.

Interview questions:

Why must updateAndGet’s function tolerate repeated evaluation?

A concurrent writer can defeat CAS, forcing a new read and another evaluation of the function.

Exact quotas, LongAdder and false sharing

Definition:

LongAdder spreads updates across a base and contention cells to reduce contention.

Explanation:

LongAdder reduces contention by using distributed cells when needed. sum during concurrent increments is not an atomic snapshot.

Illustration image:

Exact quotas, LongAdder and false sharing. Writer A → cell 0 · Writer B → cell 1 · sum reads cells · Use CAS for exact quotaExact quotas, LongAdder and false sharingSource or actorWriter A → cell 0First boundaryWriter B → cell 1Inspected statesum reads cellsObservable effectUse CAS for exact quota
Writer A → cell 0 · Writer B → cell 1 · sum reads cells · Use CAS for exact quota

Example:

Worked Java example · see surrounding context in notes
var hits = new java.util.concurrent.atomic.LongAdder();
hits.increment();
hits.add(4);
System.out.println(hits.sum());

Expected behavior. After writers stop the total is 5. Use a different primitive for admission that must enforce a precise maximum.

Internal working:

An exact quota must perform its check and update together, for example via CAS or a semaphore. False sharing can make unrelated writes contend on a cache line, so compare throughput with measured contention rather than assuming any atomic solution is faster.

Interview questions:

Can LongAdder.sum enforce an exact concurrent quota?

No. Its sum is not an atomic snapshot and a separate check and increment can admit too much work.

ABA, tagged state and access modes

Definition:

ABA occurs when state changes away and returns to a value that would satisfy an old comparison.

Explanation:

A reference can return to the same identity while the surrounding state changes.

Illustration image:

ABA, tagged state and access modes. A / 1 · B / 2 · A / 3 · Old stamp rejectedABA, tagged state and access modesSource or actorA / 1First boundaryB / 2Inspected stateA / 3Observable effectOld stamp rejected
A / 1 · B / 2 · A / 3 · Old stamp rejected

Example:

Worked Java example · see surrounding context in notes
var ref = new java.util.concurrent.atomic.AtomicStampedReference<>("A", 1);
ref.compareAndSet("A","B",1,2);
ref.compareAndSet("B","A",2,3);
System.out.println(ref.compareAndSet("A","C",1,2));

Expected behavior. Prints false because the older stamp cannot authorize the new update.

Internal working:

AtomicStampedReference compares a stamp as well as the reference. VarHandle offers plain, opaque, acquire/release and volatile access modes; mismatching access modes can break the intended publication edge. Lock-free progress is system-wide, while wait-free requires a per-operation bound.

Interview questions:

How does a stamp detect ABA?

Compare both the reference and version. A with version 3 differs from the old observation of A with version 1.

Reference subtopics

Atomic operations and functional retries

AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference target independent state. incrementAndGet returns the updated value and getAndIncrement returns the prior one. updateAndGet and accumulateAndGet may re-run their functions. Keep them side-effect-free; do not charge a payment or publish an event inside a retried transform.

Contention and exactness

LongAdder spreads increments across cells. Its sum is not an atomic snapshot during updates, so it works for metrics and is unsuitable for an exact concurrent quota. LongAccumulator applies an associative accumulation function with an identity. Use AtomicLong CAS for an exact admission limit and preserve counter bounds on release.

Low-level access and progress

Atomic arrays and field updaters make specific elements or fields atomic. VarHandle adds access modes including acquire/release; use the matching access protocol deliberately. False sharing occurs when unrelated writes invalidate a shared cache line. Lock-free guarantees system-wide progress, while wait-free bounds each operation’s progress in its own steps; a CAS retry loop may starve.

Run the complete Java labs ↗ · Java reference ↗