Java FAQ: Top Questions
26. What is the volatile keyword in Java?
The volatile keyword in Java ensures a variable’s visibility across threads, preventing thread-local caching. It’s used in multithreaded programming for lightweight synchronization.
-
Visibility:
Changes to a
volatile
variable are immediately visible to all threads. - No Atomicity: Does not guarantee atomic operations (e.g., increment).
- Use Case: Flags or status variables in multithreading (e.g., stopping a thread).
-
Performance:
Less overhead than
synchronized
but limited scope.