Without volatile, a worker thread might spin forever because it never observes a plain field change made by another thread. Marking the flag volatile guarantees the write is published, so the worker sees it and exits its loop.
class Flag {
volatile boolean stop = false;
}
Flag flag = new Flag();
int[] loops = new int[1];
Thread worker = new Thread(() -> {
while (!flag.stop) {
loops[0]++;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
break;
}
}
});
worker.start();
Thread.sleep(30);
flag.stop = true;
worker.join();
System.out.println("Worker saw the volatile flag change: " + (loops[0] > 0));
Worker saw the volatile flag change: true
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27