Junior — Middle
In what situations is it recommended to use the volatile keyword in Java?
sobes.tech AI
Answer from AI
The keyword volatile in Java is recommended to be used when a variable may be modified by multiple threads, and it is necessary to ensure the visibility of changes to this variable across threads without using full synchronization.
Main situations for using volatile:
- The variable is used for flags or status indicators that are read and written by different threads.
- It is necessary to guarantee that a write to the variable by one thread becomes immediately visible to other threads.
Important: volatile does not guarantee atomicity of operations (e.g., increment), but only guarantees visibility and ordering of reads/writes.
Example:
class Flag {
private volatile boolean active = true;
public void stop() {
active = false; // change will be visible to other threads
}
public void run() {
while (active) {
// runs while active == true
}
}
}