So I am reading this book titled Java Concurrency in Practice and I am stuck on this one explanation which I cannot seem to comprehend without an example. This is the quote:
When thread
Awrites to a volatile
variable and subsequently threadB
reads that same variable, the values
of all variables that were visible to
Aprior to writing to the volatile
variable become visible toBafter
reading the volatile variable.
Can someone give me a counterexample of why “the values of ALL variables that were visible to A prior to writing to the volatile variable become visible to B AFTER reading the volatile variable”?
I am confused why all other non-volatile variables do not become visible to B before reading the volatile variable?
Thread B may have a CPU-local cache of those variables. A read of a volatile variable ensures that any intermediate cache flush from a previous write to the volatile is observed.
For an example, read the following link, which concludes with “Fixing Double-Checked Locking using Volatile”:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html