Junior — Middle
Can you explain the principle of the 'volatile' keyword in Java and how it affects working with variables in a multithreaded environment?
sobes.tech AI
Answer from AI
The volatile keyword in Java is used to indicate that a variable's 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 or a thread-local copy.
This means that:
- When writing to a
volatilevariable, the new value immediately becomes visible to all threads. - When reading a
volatilevariable, the thread always gets the most recent value.
However, volatile does not ensure atomicity of complex operations (e.g., increment), only visibility of changes. For atomic operations, other mechanisms are needed, such as synchronized or classes from java.util.concurrent.atomic.
Example:
public class Counter {
private volatile int count = 0;
public void increment() {
count++; // NOT atomic, despite volatile
}
public int getCount() {
return count; // always the latest value
}
}
Here, volatile guarantees that calling getCount() will return the last written value, but increment() is not thread-safe due to the non-atomic count++ operation.