What is the volatile keyword in Java?
The volatile keyword in Java is a field modifier that guarantees visibility and ordering guarantees for a variable across multiple threads. Without volatile, each thread may cache a variable's value in its CPU register or L1/L2 cache, meaning writes by one thread are not necessarily visible to other threads reading the same variable.
When a variable is declared volatile, the JVM ensures two things: first, every read of that variable goes directly to main memory rather than a thread-local cache; second, every write to that variable is flushed to main memory immediately. This eliminates the stale-read problem in multi-threaded programs.
volatile also provides a happens-before guarantee: all writes that happened before a volatile write are visible to any thread that reads that volatile variable afterward. This is a weaker guarantee than synchronization — it does not provide atomicity for compound operations. For example, volatile int counter does not make counter++ thread-safe because that operation involves a read, increment, and write — three distinct steps.
The canonical use case for volatile is a boolean status flag: a background thread sets running = false and the worker thread's loop condition checks while (running). Without volatile, the JIT compiler may hoist the read out of the loop entirely, and the worker never sees the update.
volatile is not a replacement for synchronized or Lock. It is appropriate when one thread writes and others only read, or when writes are independent (not derived from the current value). For counters, accumulators, or check-then-act patterns, prefer AtomicInteger or explicit synchronization.
Explains CPU cache visibility problem and that volatile forces reads/writes to main memory. May not mention happens-before or contrast with atomicity.
Covers visibility, happens-before guarantee, why volatile does not provide atomicity for compound operations, and gives a concrete appropriate use case like a stop flag.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment