In multithreaded environments, threads can cache variables locally, leading to inconsistencies in reading shared data. Without the volatile
keyword, changes made to shared variables may not be visible across all threads immediately.
What is it?
The volatile
keyword in Java is used to mark a variable such that any write to it is immediately visible to all threads. It ensures that the variable's value is always read from and written to the main memory, preventing local thread caching.
How is it used?
By declaring a variable as volatile
, you guarantee visibility of changes across threads without using synchronization mechanisms.
private volatile boolean flag = true; public void stop() {
flag = false; // Change visible to all threads
}
public void run() {
while (flag) {
// Thread keeps running until flag is set to false
}
}
In this example, the value of flag
is immediately visible to all threads once updated.
Key points:
- volatile
ensures visibility but does not guarantee atomicity.
- It’s useful when a variable is accessed by multiple threads but only requires visibility, not complex synchronization.
When to use:
- When you need to share a simple flag or variable between threads where updates should be visible immediately without locking.
volatile
provides a lightweight alternative to synchronization for ensuring visibility of shared variables in Java.