Skip to main content
Memory model · Topic 3 of 5

Visibility with volatile

Definition​

Without volatile, a thread may keep a stale copy of a field in a CPU cache or a register and never notice that another thread changed it. A write to a volatile field happens-before every later read of it, so the reader sees the update and everything written before it.

Example code​

A flag publishes the data written before it

class Demo {
static int data;
static volatile boolean ready; // the volatile flag publishes everything written before it

public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
while (!ready) { } // wait for the flag
System.out.println("reader sees data = " + data); // guaranteed to be 42
});
reader.start();

Thread.sleep(50);
data = 42; // 1. write the data
ready = true; // 2. then set the volatile flag
reader.join();
}
}

// Output:
// reader sees data = 42

Finished this page? Track your progress (saved only in your browser).