Junior — Middle
What is the role and purpose of the volatile keyword in programming language?
sobes.tech AI
Answer from AI
The volatile keyword in Java is used to indicate that a variable's value may be changed by different threads. It guarantees that reads and writes to this variable are directly from and to the main memory, not cached in CPU caches, ensuring visibility of changes across threads.
This prevents situations where one thread does not see updates made by another thread. However, volatile does not guarantee atomicity of operations, so synchronization is still needed for complex operations.
Example:
volatile boolean flag = false;
// Thread 1
flag = true;
// Thread 2
if (flag) {
// will see the updated value
}