Atomics and compare-and-swap question 59 of 180 mid
What do getAndUpdate, updateAndGet and accumulateAndGet do, and what is the catch?
- They lock the atomic while the function runs
- Correct: They run your function inside the CAS retry loop, so the function must be pure and side-effect free because it may run several times
- They are slower versions of
set - They only work on
AtomicReference
These methods let you apply an arbitrary function atomically:
counter.updateAndGet(n -> Math.min(n + 1, max));
The implementation reads, applies the function, and CASes. On failure it re-reads and applies the function again. That is the catch: your lambda may be invoked several times for one logical update, so it must be side-effect free. Logging, incrementing a second counter or sending a message inside it will happen more than once, silently, only under contention.
Quiz yourself on Atomics and compare-and-swap Suggest a correction