Senior
What is volatile in Java?
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.
Main features of volatile:
- Ensures that a write to the variable is immediately visible to all threads.
- Prevents reordering of operations involving this variable by the compiler and processor.
- Does not guarantee atomicity of complex operations (e.g., increment), only visibility.
Example:
public class Example {
private volatile boolean flag = false;
public void writer() {
flag = true; // write is immediately visible to other threads
}
public void reader() {
if (flag) {
// will definitely see the updated value of flag
System.out.println("Flag is true");
}
}
}