Sub topic 9
volatile: Visibility Without Locking
In the visibility chapter, one thread changed a field and another thread never saw the change. A synchronized block fixes that, but sometimes a full lock is more than you need. Java has a lighter tool for this problem: the volatile keyword.
This chapter covers what volatile does, when it is the right choice, and the mistake people make with it most often.
What volatile means
A keyword is a word with a special meaning in the Java language. volatile is a keyword you put on a field. A field is a variable that belongs to a class or an object.
When a field is volatile, Java makes two promises:
- Every write is visible. When one thread writes the field, other threads see the new value the next time they read it.
- Every read is fresh. A thread cannot keep an old copy of the field and reuse it. Each read gets the latest value.
Without volatile, the processor and the compiler may keep a value in a fast, private place, such as a CPU cache (a small, fast memory close to the processor). A thread may read that private copy over and over and never notice another thread's change. volatile rules this out.
The classic use: a stop flag
A flag is a boolean field that signals something, such as "keep running" or "stop now." Stop flags are the most common place to use volatile.
public class Worker implements Runnable {
private volatile boolean running = true;
public void stop() {
running = false;
}
@Override
public void run() {
while (running) {
// do a unit of work
}
}
}Here is a program that uses it. Save it as StopDemo.java in the same folder as Worker.java.
public class StopDemo {
public static void main(String[] args) throws InterruptedException {
Worker worker = new Worker();
Thread t = new Thread(worker);
t.start();
Thread.sleep(500); // let the worker run for half a second
worker.stop(); // main thread writes running = false
t.join(); // wait for the worker to finish
System.out.println("Worker stopped.");
}
}Compile and run it:
javac Worker.java StopDemo.java
java StopDemoThe program prints Worker stopped. after about half a second.
Now remove volatile from the field and run it again. On many machines the program still works. On some machines it hangs forever. The compiler can see that the loop never changes running, so it may read the field once and turn the loop into while (true). Nothing in Java forbids that without volatile. A bug that shows up only on some machines is very hard to track down, which is why you add volatile up front.
What volatile does not do
volatile fixes visibility. It does not fix atomicity. An action is atomic when it happens as one step that no other thread can interrupt halfway.
In an earlier chapter you saw that count++ is three steps: read, add one, write. volatile makes each of those reads and writes visible. It does not stop two threads from running their three steps at the same time.
public class VolatileRace {
private static volatile int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count++; // still read, add, write: not atomic
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}Run this a few times. You will often see a total below 200000, even though count is volatile. Both threads can read the same value, say 41, and both write 42. One increment is lost.
volatile compared with synchronized
| Question | volatile | synchronized |
|---|---|---|
| Are writes visible to other threads? | Yes | Yes |
| Is `count++` safe? | No | Yes |
| Can a thread be blocked while waiting? | No, it never waits | Yes, it waits for the lock |
| Can it protect several fields together? | No, each field stands alone | Yes, everything inside the block |
| Cost | Low | Higher, especially when threads compete for the lock |
volatile never makes a thread wait, so it cannot cause a deadlock. That is one reason it is a good fit for simple flags.
When volatile is the right choice
Use volatile when all of these are true:
- The new value does not depend on the old value. Setting
running = falseis fine.count = count + 1is not. - The field stands alone. It is not part of a rule that links it to other fields, such as "
lowmust always be less thanhigh." - You only need visibility. No thread has to wait for another.
Common good uses:
- Stop and shutdown flags.
- A "ready" or "initialized" flag that one thread sets once.
- A reference to the latest settings object, which one thread replaces with a new object and many threads read.
Edge cases worth knowing
volatile on a reference covers only the reference
A reference is a variable that points to an object. If you write volatile List<String> items, the variable items is volatile. The list it points to is not. Two threads calling items.add(...) on the same ArrayList can still corrupt it. volatile only guarantees that every thread sees which list items currently points to.
Writes before a volatile write are visible too
volatile also orders the writes around it. Everything a thread writes before a volatile write is visible to another thread after that thread reads the same volatile field.
public class Config {
private String host; // plain field
private volatile boolean ready; // volatile flag
public void load() {
host = "example.com"; // 1. write the data
ready = true; // 2. then set the volatile flag
}
public String hostIfReady() {
if (ready) { // 3. read the volatile flag
return host; // 4. guaranteed to see "example.com"
}
return null;
}
}The order matters. If you set ready first and host second, the guarantee does not cover host. The Java Memory Model chapter explains this rule, called happens-before, in full.
long and double
A long or double is 64 bits. On some systems Java may write a plain long in two 32-bit halves, so another thread could read a mix of old and new halves. Marking the field volatile makes each single read and write of a long or double happen in one piece. It still does not make x++ atomic.
Summary
volatilemakes writes to a field visible to all threads and stops threads from reusing old copies.- It suits flags and single values that one thread sets and others read.
- It does not make read-modify-write actions like
count++atomic. - On a reference, it covers the reference, not the object it points to.
- Writes made before a volatile write are visible to any thread that later reads that field.
Exercise
A field is declared as private volatile int hits = 0; and four threads each run hits++ one thousand times. Will the final value always be 4000? Why or why not?
Show answer
No. volatile makes each read and write visible, but hits++ is still three separate steps (read, add one, write). Two threads can read the same value and both write the same result, so increments are lost. Use AtomicInteger or synchronized instead.
Exercise
A thread runs while (!done) { } and another thread later sets done = true. The field done is a plain boolean. What can go wrong, and what is the smallest fix?
Show answer
The looping thread may never see the change, because the compiler or CPU can keep reading an old copy of done, and the loop can run forever. The smallest fix is to declare the field as volatile boolean done.
Exercise
In the Config class, a developer swaps the two lines in load() so that ready = true comes before host = "example.com". Is hostIfReady() still guaranteed to return "example.com" when ready is true? Explain.
Show answer
No. Only writes made before the volatile write are guaranteed to be visible to a thread that reads the volatile field. With the lines swapped, host is written after ready, so a reader may see ready as true and still see host as null.