Junior — Middle
Explain the purpose and behavior of the volatile keyword 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.
Purpose of volatile:
- Ensures that reading and writing the variable occurs directly from main memory, not from the processor cache.
- Provides visibility of changes to the variable across threads — if one thread changes the value, others will immediately see the update.
Important:
volatiledoes not guarantee atomicity of complex operations (e.g., increment), only visibility.- Used for flags and simple states where synchronization blocks are not needed.
Example:
class Example {
private volatile boolean flag = false;
public void setFlag() {
flag = true; // change will be visible to other threads immediately
}
public void checkFlag() {
if (flag) {
// will execute as soon as flag becomes true
}
}
}