Java Concurrency Interview

The Java memory model question 15 of 180 junior

What does volatile guarantee, and what does it not?

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.

memory-model volatile

Quiz yourself on The Java memory model Suggest a correction