Can you explain how the volatile keyword is used in Java and what it is for?
sobes.tech AI
Answer from AI
In Java, the keyword volatile is used to denote a variable whose value may be changed by multiple threads simultaneously. It guarantees that reads and writes to this variable will happen directly from main memory, not from the CPU cache, ensuring visibility of changes across threads.
Without volatile, one thread may see a stale value of the variable, as changes made by another thread may remain in the local cache.
Example usage:
public class Example {
private volatile boolean flag = false;
public void setFlag() {
flag = true; // write is immediately visible to other threads
}
public void waitForFlag() {
while (!flag) {
// wait until flag becomes true
}
System.out.println("Flag has been changed!");
}
}
Here, volatile guarantees that when one thread changes flag, the other thread will see this change without delay.
Important: volatile only ensures visibility and ordering of operations on this variable, but does not guarantee atomicity of complex operations (e.g., increment). For atomic operations, other mechanisms are needed, such as synchronized or classes from java.util.concurrent.atomic.