Java Concurrency Interview

Atomics and compare-and-swap question 59 of 180 mid

What do getAndUpdate, updateAndGet and accumulateAndGet do, and what is the catch?

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.

atomics api

Quiz yourself on Atomics and compare-and-swap Suggest a correction