Junior — Middle
In which cases is it recommended to use the volatile keyword in Java?
sobes.tech AI
Answer from AI
The volatile keyword in Java is used for variables that may be modified by multiple threads simultaneously. It guarantees that:
- Reading the variable always occurs from main memory, not from the thread's cache.
- Writing to the variable immediately becomes visible to other threads.
It is recommended to use volatile when:
- The variable is used for flags or states that are read and written by different threads.
- Full synchronization is not necessary, but visibility of changes is required.
Example:
public class Flag {
private volatile boolean active = false;
public void activate() {
active = true; // change will be visible to other threads immediately
}
public boolean isActive() {
return active; // always current value
}
}
Important: volatile does not guarantee atomicity of complex operations, only visibility of changes.