Junior — Middle
What behavior is ensured by using the volatile keyword in a 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 at any moment by different threads. It guarantees that:
- Reading and writing the variable will occur directly from main memory, not from the processor cache.
- Changes made by one thread to the variable are immediately visible to other threads.
This helps avoid caching issues and ensures correct handling of variables in a multithreaded environment without using heavier synchronization mechanisms.
Example:
volatile boolean flag = false;
// One thread changes flag
flag = true;
// Another thread sees the updated value of flag without delays
if (flag) {
// perform actions
}