Java Reference ยท Concurrency
volatile and the Java memory model
Reference for the Java memory model: what volatile guarantees, happens-before rules, safe publication, final fields and why volatile counters still break.
Threads do not always see each other's writes. The compiler, the JIT and the CPU may reorder operations and keep values in registers or per-core caches. The Java Memory Model (JMM) defines exactly when a write by one thread is guaranteed to be visible to a read in another: when there is a happens-before relationship between them. Without one, a reader may see a stale value, a partly constructed object, or never see the change at all.
volatile is the simplest tool for creating that relationship. A write to a volatile variable happens-before every later read of the same variable, and everything the writer did before the write becomes visible to a reader that sees it. The keyword itself is described on volatile; this page explains the rules behind it.
private volatile boolean running = true; void stop() { running = false; } // write void loop() { while (running) { /* work */ } } // read: sees the change
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Concepts
The happens-before rules
If action A happens-before action B, then B sees everything A did. The JMM defines these edges:
| Rule | Edge |
|---|---|
| Program order | Each action in a thread happens-before the next one in that same thread. |
| Monitor lock | Unlocking a monitor happens-before every later lock of the same monitor. |
| Volatile | A write to a volatile variable happens-before every later read of it. |
| Thread start | Thread.start() happens-before every action in the started thread. |
| Thread end | Every action in a thread happens-before another thread detects its end (join(), isAlive() == false). |
| Interruption | A call to interrupt() happens-before the interrupted thread detects it. |
| Final fields | Writes to final fields in a constructor are visible to every thread that gets the object, provided this did not escape during construction. |
| Transitivity | If A happens-before B and B happens-before C, then A happens-before C. |
Locks, atomics, Future.get(), concurrent collections and CountDownLatch are all built on these rules.
What volatile does and does not do
- Does: guarantees visibility and ordering for that variable, and (for
longanddouble) makes reads and writes atomic. - Does not: make compound actions atomic.
count++is a read, an add and a write; two threads can both read 5 and both write 6. UseAtomicInteger,LongAdderor a lock. - Does not: protect an object's contents. A
volatile Listreference is visible, but the list's elements are not safe because of it.
Safe publication
An object is safely published when its reference reaches other threads through a happens-before edge. The common ways:
- store it in a
volatilefield or anAtomicReference, - store it in a field guarded by a lock that readers also use,
- put it in a concurrent collection or a
BlockingQueue, - initialize it in a static initializer (class initialization is thread-safe),
- make all its fields
final.
Publishing through a plain field is a data race: another thread may see the reference but stale or default values in the object's fields.
Usage notes
- Double-checked locking needs
volatile.private volatile Helper helper;is the correct form; without it a thread can see a half-constructed object. - Busy loops on plain fields may never end. The JIT may hoist the read out of the loop. A
volatileflag, an interrupt or aThread.onSpinWait()hint with a volatile condition fixes it. - Prefer higher-level tools (
BlockingQueue,CountDownLatch,CompletableFuture) over hand-built flags. - Fine-grained control exists in
VarHandle(getAcquire,setRelease,compareAndSet) and inAtomicXxx.getPlain/lazySet, for library authors only. - A data race is a program bug, not just stale data: the JMM only guarantees sequential consistency for race-free programs.
- Cost. Volatile accesses are cheap on x86 reads, more expensive on writes, but far cheaper than locks.