What does the volatile keyword guarantee in Java, and what does it deliberately not guarantee?
The keyword volatile gives you two guarantees, and it deliberately leaves one thing out.
The first guarantee is visibility. When one thread writes to a volatile field, the value becomes visible to the other threads promptly, without any locking and without waiting for them to be scheduled.
The second guarantee is ordering. The reads and writes around a volatile field cannot be moved across it by the compiler or by the processor. So everything that a thread did before the volatile write is visible to a thread that reads the volatile field afterwards.
public class Main {
public static void main(String[] args) throws InterruptedException {
// A volatile flag. The writer's value becomes visible promptly.
Stopwatch stopwatch = new Stopwatch();
stopwatch.running = true;
Thread reader = new Thread(new Runnable() {
public void run() {
try {
while (stopwatch.running) {
// The loop keeps going until the flag is seen as false.
}
System.out.println("the reader saw the change");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
reader.start();
Thread.sleep(50);
stopwatch.running = false;
reader.join();
}
}
class Stopwatch {
volatile boolean running = true;
}
So what does it deliberately not guarantee? It does not make a compound operation atomic.
The operation count++ is really three steps. It reads the value, it adds one, and it writes it back. If two threads do that at the same time, they can both read the same value and both write the same answer, and one of the increments is lost. The volatile keyword says that each of the three steps is seen by the other thread, and it says nothing at all about the three of them happening together.
So the rule is this. Use volatile for a flag that one thread sets and another thread reads, and for a value that is written by one thread and read by another with nothing else happening in between. Do not use it for a counter that more than one thread changes.
The next question in this topic looks at when to reach for it and when to reach for something else.