A frequently misunderstood keyword
The meaning of volatile differs sharply between languages, and confusing them causes bugs.
In C and C plus plus
Here volatile means every access touches memory rather than a cached register copy, and accesses are not reordered with other volatile accesses. It was designed for memory mapped hardware registers where a read can have side effects. It does not provide atomicity, does not order against ordinary variables, and does not insert the fences needed for thread synchronization.
In Java
Java volatile is stronger. A volatile write has release semantics and a volatile read has acquire semantics, so it can publish data safely between threads and forbids the compiler from caching the value.
The common trap
- Using C volatile as if it synchronizes threads is a classic mistake.
- It stops the compiler from caching the variable but says nothing to other cores or about other data.
For portable thread communication, prefer real atomics with explicit ordering rather than relying on any volatile interpretation.
Key idea
C volatile only forces memory access and is not thread synchronization, while Java volatile adds acquire release ordering, so know which language you are in.