What does the volatile keyword guarantee in Java, and what does it not guarantee?
volatile guarantees visibility: a write to a volatile field is immediately flushed to main memory, and every subsequent read of that field loads directly from main memory rather than a possibly stale CPU cache. It also establishes a happens-before relationship, meaning a volatile write happens-before every subsequent volatile read of the same field, which forces the JVM and CPU to keep earlier writes properly ordered and visible. What volatile does not guarantee is atomicity for compound operations: with a declaration like volatile int x, the statement x++ is still a race condition, because increment is a read-modify-write sequence made of three separate, non-atomic steps. To get atomic compound operations you need a class like AtomicInteger instead of a bare volatile field.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response