Java / volatile
What guarantee volatile variable provides? (OR) The Java volatile Happens-Before Guarantee
Since Java 5 the volatile keyword guarantees more than just the reading from and writing to main memory of variables.
If Thread A writes to a volatile variable and Thread B subsequently reads the same volatile variable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.
Developers may use this extended visibility guarantee to optimize the visibility of variables between threads. Instead of declaring each and every variable volatile, only one or a few need be declared volatile.
Thread A:
sharedObject.myNonVolatileVar = 123; sharedObject.myVolatileVar = sharedObject.myVolatileVar + 1;
Thread B:
int myVolatileVar = sharedObject.myVolatileVar; int myNonVolatileVar = sharedObject.myNonVolatileVar;
More Related questions...