Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is the purpose of the volatile keyword?
volatile guarantees visibility: whenever a thread writes to a volatile field, that write is immediately flushed to main memory, and any thread that subsequently reads the field is guaranteed to see the latest value rather than a stale, cached copy.
It also prevents the compiler and CPU from reordering instructions around that read/write, which matters for constructs like the double-checked locking pattern.
private volatile boolean running = true; void stop() { running = false; } // writer thread void loop() { while (running) { /* work */ } } // reader thread sees the update
What volatile does not do is provide atomicity for compound operations. An expression like counter++ on a volatile int is still a read-modify-write sequence that two threads can interleave, causing lost updates. For atomic compound operations you need synchronized or classes like AtomicInteger.
More Related questions...