volatile
volatile makes reads and writes of a field visible across threads and prevents some reorderings. It does not make count++ atomic. Use it for simple flags and for safe publication of a well-formed object.
Detailed Explanation
Without a happens-before edge, a thread can run forever seeing ready == false after another thread set ready = true. The compiler and CPU may cache the field in a register. volatile forbids that cache for that field. A write to a volatile happens-before every later read of the same field. The reading thread also sees all writes that were visible to the writer before that volatile write.
That is why the idiom instance = new Holder(); done = true; with done volatile publishes instance safely if the reader only looks at instance after seeing done. Double-checked locking uses a volatile instance field for the same reason.
volatile is not a lock. count++ is still read, add, write. Two threads can lose an increment. volatile long and double are atomic (Java 5+), unlike non-volatile 64-bit fields on some older stories, but ++ is still not atomic. Use AtomicInteger for counters.
You reach for volatile for a shutdown flag (while (!stopped)), for a published immutable config snapshot, and for the instance field in safe lazy init. You reach for synchronized or an atomic when you read-modify-write. You reach for a final field and safe construction when the object is published once through a data race-free path (constructor freeze).
The cost of volatile is a memory barrier on each access. Do not spray it on every field. The cost of using it as a lock is a race. The cost of a volatile array is that only the array reference is volatile, not the slots; volatile int[] does not make xs[i] = 1 visible in the way people hope. Use AtomicIntegerArray or synchronize.
A thread that spins on a non-volatile flag can livelock in a loop the JIT never re-reads. That bug looks like "the other thread never ran".
Code Examples
public class Stop {
private volatile boolean stopped;
public void stop() {
stopped = true;
}
public void loop() {
while (!stopped) {
// the read sees the write from stop()
}
}
public static void main(String[] args) throws InterruptedException {
Stop s = new Stop();
Thread t = new Thread(s::loop);
t.start();
s.stop();
t.join();
System.out.println(s.stopped); // prints: true
}
}import java.util.concurrent.atomic.AtomicInteger;
public class NotEnough {
private volatile int count;
public void incBroken() {
count++; // still a race
}
private final AtomicInteger safe = new AtomicInteger();
public void incSafe() {
safe.incrementAndGet();
}
}Common Gotchas
`volatile` does not make `++` atomic
use `AtomicInteger` or a lock.
`volatile T[]` does not make elements volatile
each slot needs atomics or a lock.
A volatile write publishes earlier writes from that thread
readers that see the volatile write see those too.
Spinning on a non-volatile flag can never observe the update
Spinning on a non-volatile flag can never observe the update