What is the significance of the volatile keyword in Java concurrency?

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.

Key Points: • Without volatile, one thread's write to a variable might sit in a CPU cache or register and not become visible to other threads for an indeterminate amount of time. • volatile also prevents certain compiler and processor reorderings around the variable, which matters for correctness under the Java Memory Model. • It's cheaper than synchronization since it doesn't involve acquiring a monitor or blocking other threads, only enforcing visibility and ordering. • It does not make compound actions (like increment) atomic, so it's not a substitute for locking when multiple related operations need to happen together. • A classic use case is a flag checked in a loop by one thread and set by another to signal it should stop.

Example: 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.

Code Example:

private volatile boolean stopRequested = false;

public void requestStop() {
    stopRequested = true;
}

public void run() {
    while (!stopRequested) {
        // work
    }
}

Interview Tip: 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."