I have encountered the following claim: "Reading or writing to a volatile variable imposes a memory barrier in which the entire cache is flushed/invalidated."
Now consider the following execution scenario:
initial volatile boolean barrier;
initial int b = 0;
thread 1 b = 1; // write1
thread 1 barrier = true; // write2
thread 2 barrier = true; // write3
thread 2 print(b); // r1
Question: is thread 2 guaranteed to print 1?
Based on the claim, I would answer yes: thread 1 flushes its cache on write2 (so that b = 1
ends up in main memory), and thread 2 invalidates its cache on write3 (so that it will read b
from main memory).
However, in the relevant JLS sections I am unable to find a guarantee for this behaviour, since write3 is a write, and not a read. Thus the following seemingly crucial clause does not apply:
A write to a volatile variable v (§8.3.1.4) synchronizes-with all subsequent reads of v by any thread (where "subsequent" is defined according to the synchronization order).
Is there some other information I am missing, or am I perhaps misunderstanding something?
(Relevant questions: