Junior — Middle
What behavior does the volatile keyword ensure in Java when working with variables?
sobes.tech AI
Answer from AI
The volatile keyword in Java guarantees that reading and writing a variable will occur directly from main memory, not from the processor cache or thread-local copy. This ensures:
- Visibility of changes: when one thread modifies the value of a volatile variable, other threads will immediately see this change.
- Prevents reordering: operations on a volatile variable will not be reordered by the compiler or processor relative to other operations.
Example of usage:
public class Flag {
private volatile boolean active = true;
public void stop() {
active = false;
}
public void run() {
while (active) {
// perform work
}
}
}
Here, without volatile, the thread executing run() might not see the change to active in the stop() method. With volatile, it is guaranteed that the loop will terminate when active becomes false.