KatInterview

What Java's volatile Does and Does Not Guarantee

Data Structure DesignModel answer
MediumModel answerData Structure Designjavaconcurrencymemory-model

Last updated

Explain the Java Memory Model guarantees of volatile fields: visibility, happens-before ordering and reordering limits, its gaps such as compound atomicity, and when to prefer locks or atomics.

You are reviewing a concurrent Java codebase and need to explain to a teammate exactly what marking a field volatile buys them.

Write an answer that covers:

  1. Visibility. What happens when one thread writes a volatile field and another reads it?
  2. Ordering. How does volatile create a happens-before relationship, and what does this imply for other, non-volatile data written beforehand?
  3. Reordering. Which reorderings by the compiler, JIT or CPU are forbidden around volatile reads and writes, and which are still allowed?
  4. Limits. What does volatile not provide? Use at least one concrete broken example, such as a counter incremented from several threads.
  5. Comparison. How does it differ from synchronized/ReentrantLock and from atomic classes such as AtomicInteger?
  6. Use cases. Give a few situations where volatile is the right tool and a few where it is not.

Short code snippets are welcome. Be precise about what is guaranteed versus what merely tends to happen on typical hardware.

Hints

Hint 1

Think in terms of the Java Memory Model's happens-before relation rather than 'flushing to main memory'. What does a volatile write establish with respect to a later volatile read that observes it?

Hint 2

Describe a volatile write as a release and a volatile read as an acquire. Which operations may not cross each of them, and which ordinary operations may still move into the protected region?

Hint 3

Take `count++` on a volatile int and trace it as read, add, write across two threads. Then ask which tools (atomics, locks) fix that problem and which scenarios, like a single-writer stop flag, do not need them.