Junior — Middle
What is the purpose of the volatile keyword in programming?.
sobes.tech AI
Answer from AI
The keyword volatile is used to tell the compiler that the value of a variable may change at any time outside the control of the current thread of execution, for example, by hardware or another thread. This prevents optimizations that might cache the variable's value in a register and not update it from memory.
In multithreaded programming, volatile guarantees that reading and writing a variable will occur directly from memory, ensuring visibility of changes between threads. However, volatile does not guarantee atomicity of operations and does not replace full synchronization.
Example in Java:
volatile boolean flag = false;
// Thread 1
flag = true;
// Thread 2
if (flag) {
// will see the updated value
}
Here, without volatile, Thread 2 might not see the update to flag.