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:
Example:
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.