☕ Java
Intermediate
What is the volatile keyword in Java?
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.
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?