Sub topic 9
volatile: Visibility Without Locking
In the last chapters you saw two separate problems. Atomicity means a group of steps happens as one step. Visibility means one thread can see a value that another thread wrote. The volatile keyword fixes visibility, and it does so without a lock.
What volatile Means
A keyword is a reserved word that has a special meaning in Java. volatile is a keyword you put on a field. It tells Java that the field is shared between threads.
When a field is volatile:
- Every write goes straight to main memory, where all threads can see it.
- Every read gets the latest value from main memory. It does not use an old copy held in a CPU cache.
So when one thread changes a volatile field, other threads see the new value the next time they read it.
A Worked Example: A Stop Flag
A flag is a boolean field that tells code when to stop or start. A common use is to ask a worker thread to stop.
public class Worker implements Runnable {
private volatile boolean running = true;
public void stop() {
running = false;
}
@Override
public void run() {
long loops = 0;
while (running) {
loops++;
}
System.out.println("Worker stopped after " + loops + " loops");
}
public static void main(String[] args) throws InterruptedException {
Worker worker = new Worker();
Thread t = new Thread(worker);
t.start();
Thread.sleep(500);
worker.stop();
t.join();
System.out.println("Main thread done");
}
}The main thread calls stop(), and the worker sees running become false and leaves its loop. If you remove volatile, Java is allowed to keep reusing an old copy of running. The worker might then loop forever.
What volatile Does Not Do
volatile does not make compound actions atomic. A compound action is several steps that need to act as one, such as count++, which reads, adds, and writes.
When to Use volatile
| Situation | Is volatile enough? |
|---|---|
| One thread sets a stop flag, others read it | Yes |
| Publishing a value that is written once and read by many | Yes |
| Incrementing a shared counter | No |
| Check a value, then change it based on that check | No |
A simple test: volatile is enough when each write stands alone and does not depend on the old value.
Exercise
A field is declared private volatile int hits = 0; and four threads each run hits++ 1,000 times. Is the final value always 4,000? Why or why not?
Show answer
No. volatile makes every write visible, but hits++ is still three steps: read, add one, write. Two threads can read the same value and both write the same result, so an update is lost. Use synchronized or AtomicInteger instead.
Exercise
Why might the Worker loop never end if running is not volatile?
Show answer
Without volatile, Java may let the worker thread keep reading an old cached value of running, so it never sees the main thread's write of false.