How to understand “consistency before occurrence is not enough” in Java

In Chapter 17 of Java language specification, there was a part explaining why "lack of consistency" Here is an example:

At first,x = y = 0
Thread 1            | Thread 2
r1 = x;             | r2 = y; 
if (r1 != 0) y = 1; | if (r2 != 0) x = 1;

Here is a possible execution trace:

r1 = x;  // sees write of x = 1
y = 1;
r2 = y;  // sees write of y = 1
x = 1;

How could this happen? I'm confused that when the first action sees x = 1, it doesn't mean condition R2= 0 becomes true, so y has been assigned to 1 But in this order, y = 1 after R1 = X Where did I get the wrong example? How can I correctly explain this example?

Solution

I believe that the view of this example in the Java specification is that Hans Boehm et al. Wrote it in outgoing ghosts, which pointed out the defects of the memory model of some contemporary languages (Java, C 11, or even C 14, still solved, but did not solve this problem)

The point is this: the program is correctly synchronized by the rules of the language according to the written rules (in C, if you use atomic variables and memory_order_relaxed, it's everywhere) but there's still no unexpected behavior Description Boehm: the machine can guess the value of X, for example, X is 1, then execute the result branch, and later (probably when the memory finally responds) verify whether the guess is true Speculation is indeed found, because x = 1 is indeed stored in another thread, and the machine continues and does not roll back the speculative execution

Worse, the CPU can really speculate about any value Consider an example of this modification:

r1 = x                     |  r2 = y
if (r1 != 0) y = r1        |  if (r2 != 0) x = r2

In this case, X and Y may end up with any value for the same reason The machine can speculate what the value is, then speculate to continue to implement this hypothesis, and later find that its speculation is true, in the proverbial self fulfilling prophecy

It may be reassuring that there is no real hardware performance so far But the key is that the memory model of contemporary language can not prevent this behavior The part you refer to is java trying to say, "look, we need to happen before consistency, but this other strange thing should not happen here." In non normative note 1.10/25, C 14 has the same vague opinion on this issue

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>