Java memory model: volatility and read / write volatility

I'm having trouble understanding how JMM relates to reordering possible instructions. For example, consider the following code snippet:

volatile boolean t1HasArrived = false, t2HasArrived = false;

// In thread 1
t1HasArrived = true;
while (!t2HasArrived) 
    ;

// In thread 2
t2HasArrived = true;
while (!t1HasArrived)
   ;

Now I want to believe that this code implements Barrier synchronization for two threads. But I'm not so sure about that. What makes me doubtful is the read / write reordering: is there anything in JMM that would prevent the compiler or processor from rebuilding the code execution path, for example, the code snippet below? And if not, how do you actually prove that such reordering is allowed?

// In thread 1
while (!t2HasArrived)
    ; 
t1HasArrived = true;

// In thread 2
while (!t1HasArrived)
   ;
t2HasArrived = true;

, . , , . , JMM. , /, , .

+4
2

JMM.

, , , . Java.

. JSR-133 .


Lasciate ogni speranza, voi chentrate.

JSR-133:

§5

. - , , . , , .

. , , , , , , , .

§7.3

. E =

, :

  1. . , , , : , . , , , .
+4

JMM . , JVM .

, , volatile. , , , .

, , , , , . , , , , JMM , .

JMM, ( - 7 , 27 ).

+3

Source: https://habr.com/ru/post/1614208/


All Articles