Examples of thread divergence actions and external actions in the Java memory model

I am currently researching the Java memory model and I have come to different types of Action .

There are two of them that I don't quite understand:

  • External actions and
  • Stream divergence actions

Please explain these two types of actions and give examples for them and their special properties in relation to compilation-reordering and happen-before relationships . Oh, and are native calls also external actions?

I think they will not detect diverging flows unless there is anything special about them. So what makes them special so that they need to be defined as a special kind of action?

+3


source to share


2 answers


The existing answer already correctly defines what these actions are.

Regarding reordering: look at the following example of stream divergence action:

class ThreadDivergence { 

  int foo = 0; 

  void thread1() { 
    while (true); // thread-divergence action
    foo = 42; 
  } 

  void thread2() { 
    assert foo == 0; 
  } 
}

      

You expected this statement to never fail. Without threading actions, this cannot be guaranteed, because an invalid install definition foo = 42

might be reordered to execute first. This is prohibited by JMM.



Likewise, external actions are added to avoid unexpected results:

class Externalization { 

  int foo = 0; 

  void method() { 
    jni(); // external action
    foo = 42; 
  } 

  native void jni(); /* { 
    assert foo == 0; 
  } */ 
}

      

Assuming a JNI method was implemented to accomplish the same statement, you don't expect this to fail. The JIT compiler cannot determine the result of anything external, so the JMM also disallows such reordering.

+4


source


If I understand correctly, an external action is something visible outside the Java VM process, like displaying a window, writing to a file, or connectiong to a socket.



The divergence action must go into an infinite loop while(true)

.

0


source







All Articles