Java – synchronization – reordering obstacles in two directions with the edegs Compiler?
I have a question about the JAVA memory model The following examples are given:
action 1 action 2 synchronized(monitorObject) { //acquire action 3 } //release action 4
The acquisition and release can be any synchronization with the edge (locking, unlocking, starting thread, connecting thread, detecting thread interrupt, volatile write, volatile read, etc.)
Is it guaranteed that action 3 cannot be moved before acquisition and cannot be moved after release?
And ensure that act 2 cannot move after acquisition (neither before nor after release), and act 4 cannot move before release (before and after acquisition)?
Synchronization – reordering actions with the edge "two-way barrier" Compiler?
Edit 1 I worry about this because if the synchronization edge is not a bidirectional reordering barrier, the compiler may create a deadlock by moving lock acquisition to another method
Or is there a bidirectional reordering barrier that does not even need to be prevented because lock acquisition cannot be pushed into others because it will change the synchronization order?
Edit 2 actions 1, 2, 3 and 4 are "inter thread actions" defined by JMM
Edit 3 this is an example of how reordering can cause deadlocks:
X and y are shared variables, and synca and syncb can be obtained by any other thread However, using the following code, there is no possible deadlock
/* 1 */ synchronized(syncA) { /* 2 */ x = 1; /* 3 */ } /* 4 */ y = 0; /* 5 */ synchronized(syncB) { /* 6 */ y = 1; /* 7 */ }
However, if the acquisition of synca is reordered into syncb block, it may cause deadlock:
y = 0; synchronized(syncB) { y = 1; synchronized(syncA) { x = 1; } }
I don't think this is a legitimate compiler conversion because it changes the synchronization order Do I have this assumption? Which part of the Java Memory Model (JMM) allows / prohibits this?
Solution
Thank you for your assylias link to this question, which contains the answer to this image from jsr-133 Cookbook:
According to this image, it is illegal for the editor to convert from edit 3 because it rearranges two monitorentries
In addition, the table also shows which synchronization edges are what kind of "reordering obstacles" for other operations
Thank you for your help:)