Senior
What is a volatile variable and what is it used for?
sobes.tech AI
Answer from AI
In Java, the keyword volatile is used to denote a variable whose value may be changed by different threads. It guarantees that reading and writing this variable will occur directly from main memory, not from the local CPU cache, ensuring visibility of changes between threads.
Main features of volatile:
- Ensures visibility of variable changes to all threads
- Prevents reordering of read/write operations with this variable by the compiler and processor
- Does not guarantee atomicity of complex operations (e.g., increment)
Example of usage:
public class Example {
private volatile boolean flag = false;
public void setFlag() {
flag = true; // change will be immediately visible to other threads
}
public void waitForFlag() {
while (!flag) {
// wait until flag becomes true
}
// continue work
}
}
Without volatile, a thread executing waitForFlag might never see the change to flag, as the value could be cached locally.