The volatile keyword in Java guarantees that reads and writes to a variable are always visible across threads immediately, by forcing every access to go directly to main memory instead of a thread-local CPU cache, without requiring full mutual-exclusion locking.
A background worker checking while (!stopRequested) in a loop needs stopRequested declared volatile, or the JIT compiler and CPU caching could let the worker thread keep reading a stale, cached "false" value even after another thread sets it to true.
private volatile boolean stopRequested = false;
public void requestStop() {
stopRequested = true;
}
public void run() {
while (!stopRequested) {
// work
}
}A concise interview answer is
volatile guarantees that a write to a variable by one thread becomes immediately visible to reads by other threads, by routing access through main memory and preventing certain reorderings, without the overhead of locking. It solves visibility, not atomicity, so it's ideal for simple flags but not for compound operations like counters.
Last updated: 16 July 2026
Previous question: Explain the synchronized keyword in Java. How does it work?
Next question: How does the introduction of Lambda expressions change the way Java handles concurrency?