The Java memory model question 15 of 180 junior
What does volatile guarantee, and what does it not?
- It makes
counter++atomic - Correct: It gives visibility and ordering for reads and writes of that field, but no atomicity for compound actions
- It locks the object while the field is written
- It only prevents caching, not reordering
A volatile write is guaranteed to be seen by any subsequent volatile read of the same field, and it carries with it everything written before it (release/acquire semantics). It also forbids the compiler from hoisting the read out of a loop, which is what makes a plain flag loop hang forever while a volatile one exits.
What it does not do is make read-modify-write atomic. count++ is a read, an add and a write;
another thread can slip between them whatever volatile says. For a counter you want AtomicInteger
or LongAdder; for a flag or a "publish this reference once" field, volatile is exactly right.
A runnable demonstration of both halves: VisibilityExample.