We do not know what value the System.out.println(x);
instruction will see System.out.println(x);
for several reasons:
A thread can read the value set in it (regardless of whether it was set earlier or later of another thread) or the value set in another thread. Since there is no guarantee what value the stream will read.
In view of the fact that it is impossible to determine the execution time of an instruction in different threads relative to other threads - it is not known at what point the threads will execute instructions x = 10
and flag = true
relative to each other.
Relatively happens-before what happens with a volatile
variable. In this case, if the reading of a volatile
variable occurs after writing it to a variable, then the read operation MUST be able to see the βnewβ data. In this case, it only tells us that the thread that is in the loop will exit it as soon as the flag = true
instruction is executed. But again, we donβt know when flag = true
will be executed; it can be executed either before or after reading (one or several) values ββfrom a volatile
variable in the spawned thread.
It should be noted that the relation depicted in the picture in the Nofate answer should not be interpreted as a mandatory procedure by induction or locking the reader until the value of the volatile
variable is set.
βWriting to the variable x is guaranteed to happen before reading it.β
The stream will simply be in an infinite loop until flag = true
.
x = 5
and vice versa. As far as I understand, happens-before in this case applies only to theflag
, so two different threads can exist with different values ββ.. - etki