A common confusion
Developers often reach for volatile expecting it to make compound operations thread safe. In Java, volatile gives visibility and ordering but does not make read modify write sequences atomic. In C and C plus plus, volatile is even weaker and is the wrong tool for threading entirely.
What Java volatile does
- A read of a volatile field is an acquire, and a write is a release, so writes become visible across threads with happens before ordering.
- It prevents the compiler from caching the field in a register or reordering across it.
- It does not make count plus plus atomic, because that is a read, an add, and a write, three steps a second thread can interleave.
When to use atomics instead
For atomic increment, compare and set, or any read modify write, use an atomic type such as AtomicInteger or std atomic with fetch add. These provide both the visibility of volatile and true indivisible updates. The C and C plus plus keyword volatile is for memory mapped hardware registers, not inter thread synchronization.
Key idea
Volatile provides visibility and ordering but not atomic read modify write, so use real atomic types whenever an update reads then writes the same value.