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
A
writes to a volatile
variable and subsequently threadB
reads that same variable, the values
of all variables that were visible to
A
prior to writing to the volatile
variable become visible toB
after
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?
Best Answer
Declaring a volatile Java variable means:
Just for your reference, When is volatile needed ?
From JLS §17.4.7 Well-Formed Executions
Useful Link : What do we really know about non-blocking concurrency in Java?