What is the volatile keyword in Java?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
The volatile keyword ensures that a variable's value is always read from and written to main memory, not from a thread's local cache. Without volatile, each thread may cache a variable's value locally, leading to stale reads where one thread sees an outdated value. Making a field volatile guarantees visibility — all threads see the most recent write. However, volatile does NOT guarantee atomicity. For example, count++ involves three steps (read, increment, write) and is not atomic even on a volatile variable. For compound actions, use synchronized or java.util.concurrent.atomic classes like AtomicInteger.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Java answers easy to follow.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?