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?
source to share
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.
source to share