Going through the JLS by James Gosling, I came across this-
The Java programming language provides a second mechanism (other than synchronisation), volatile fields, that is more convenient than locking for some purposes.
A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable.Then the author points to this resource.
It may appear that the result r2 == 2
and r1 == 1
is impossible.
But why?
Isn't it makes perfect sense to think of something like this-
Instruction 4 : A = 2;
Instruction 1 : r2 = A;
Instruction 2 : B = 1;
Instruction 3 : r1 = B;
And the rest I couldn't understand it either.
It may appear that the result r2 == 2 and r1 == 1 is impossible. Intuitively, either instruction 1 or instruction 3 should come first in an execution. If instruction 1 comes first, it should not be able to see the write at instruction 4. If instruction 3 comes first, it should not be able to see the write at instruction 2.
If some execution exhibited this behavior, then we would know that instruction 4 came before instruction 1, which came before instruction 2, which came before instruction 3, which came before instruction 4. This is, on the face of it, absurd.
However, compilers are allowed to reorder the instructions in either thread, when this does not affect the execution of that thread in isolation. If instruction 1 is reordered with instruction 2, as shown in the trace in Table 17.4-B, then it is easy to see how the result r2 == 2 and r1 == 1 might occur.
Please exemplify.