Skip to main content
Synchronization and locks · Topic 3 of 8

volatile

Definition​

A volatile field is always read from and written to main memory, so a change made by one thread becomes visible to the others straight away. It guarantees visibility, but not that compound steps such as count++ are atomic.

Example code​

A stop flag that another thread is guaranteed to see

class Demo {
static volatile boolean running = true; // without volatile the loop might never see the change

public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long loops = 0;
while (running) loops++; // keeps looping until the flag changes
System.out.println("worker stopped");
});
worker.start();

Thread.sleep(100);
running = false; // visible to the worker immediately
worker.join();
}
}

// Output:
// worker stopped

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