Junior — Middle
Explain what the volatile keyword means in programming and what it is used for.
sobes.tech AI
Answer from AI
The volatile keyword in Java is used to indicate 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 thread's cache. This prevents situations where one thread sees an outdated value of the variable.
Example:
public class Counter {
private volatile int count = 0;
public void increment() {
count++; // without additional synchronization, this is not atomic, but volatile guarantees visibility of changes
}
public int getCount() {
return count;
}
}
It is important to understand that volatile only provides visibility of changes, not atomicity of operations.