liveBook · Manning

atomicCompareAndSet

As explained in Data-Oriented Programming: Reduce software complexity

An atomic conditional-update operation that sets state to a new value only when it equals a supplied old value.

atomicCompareAndSet conditionally changes shared state: it writes a new value only when the current state still equals the supplied old value, returning true on success and false otherwise. section 8.2

Updating a counter without a mutex

A swap operation reads a snapshot, computes the next value, and calls atomicCompareAndSet. If another thread changed the state meanwhile, the comparison fails and swap retries with a fresh snapshot. A counter can therefore apply x + 1 without wrapping the update in an explicit lock. section 8.2

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains the success condition, failure result, CPU-supported compare-and-swap basis, and retrying swap loop.
Examples
Demonstrates a thread-safe counter increment implemented through Atom.swap and atomicCompareAndSet.
What it assumes
Assumes shared-state concurrency and atoms, while introducing the conditional update operation through a counter example.
What you can do after
Build it from scratch as the conditional primitive behind a retrying, thread-safe Atom.swap operation.
How it connects
Connects atomicCompareAndSet with atoms, swap, compare-and-swap, mutexes, and Java AtomicReference.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.