Examples for thread divergence actions and external actions in the Java Memory Model

删除回忆录丶 提交于 2019-12-23 17:56:50

问题


I'm currently learning about the Java Memory Model and I came about the different kinds of Actions.

There are two of them which I don't fully understand:

  • External Actions and
  • Thread divergence actions

Please explain those two action types and give examples for them and for their special properties regarding compiler-reordering and happens-before relation. Oh, and are native calls also external actions?

I think they wouldn't define thread divergence actions if there was nothing special about them. So what makes them special so that they need to be defined as a special kind of action?


回答1:


The existing answer already correctly defines what these actions are.

As for the reordering: look at the following example of a thread-divergence action:

class ThreadDivergence { 

  int foo = 0; 

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

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

You would expect this assertion to never fail. Without thread-divergence actions, this could not be guaranteed because the unreachable definition of setting foo = 42 could be reordered to be executed first. This is forbidden by the JMM.

Similarly, external actions are added to avoid surprising outcomes:

class Externalization { 

  int foo = 0; 

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

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

Assuming that the JNI method was implemented to run the same assertion, you would not expect this to fail. The JIT compiler cannot determine the outcome of anything external such that the JMM forbidds such reorderings, too.




回答2:


If I understand correctly, External Action is something visible outside of the Java VM process, such as displaying a window, writing to a file or connectiong to a socket.

Thread Divergence Action must be entering an infinite while(true) loop.



来源:https://stackoverflow.com/questions/26788260/examples-for-thread-divergence-actions-and-external-actions-in-the-java-memory-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!