Verified Jobs Live
Java Medium Level ~3 min read

Why does volatile not make counter++ thread-safe, and what would you use instead?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

volatile provides visibility and ordering guarantees for accesses to the field, but increment is a read-modify-write sequence. Two threads can read the same value and both write the same incremented result, losing an update. AtomicInteger.incrementAndGet provides an atomic increment; synchronized or a lock can protect a larger invariant involving several fields. Pick the mechanism according to what must change together. An atomic counter does not automatically make associated collection updates atomic or make every operation in the surrounding method thread-safe.