I have a question regarding the Java Memory Model. Given the following example:
action 1
action 2
synchronized(monitorObject) { //acquire
action 3
} //release
action 4
acquire
and release
can be any synchronizes-with edge (lock, unlock, start thread, join thread, detect thread interruption, volatile-write, volatile-read, etc.)
Is it guaranteed that action 3
can't be moved before the acquire and can't be moved after the release?
And is it guaranteed that action 2
can't be moved after the acquire (neither before nor after the release) and that action 4
can't be moved before the release (neither before nor after the acquire)?
So are synchronizes-with edges "bidirectional barriers" for the compiler's re-ordering actions?
EDIT 1 I am concerned about this because if synchronizes-with edges were not bidirectional re-ordering barriers, the compiler could simply create a deadlock by moving lock acquires into others.
Or are bidirectional re-ordering barriers not even necessary to prevent this because lock acquires can't be pushed into others because that would change the synchronization order?
EDIT 2 The actions 1, 2, 3 and 4 are "inter-thread actions" as defined by the JMM.
EDIT 3 Here's an example that shows how reordering might cause a deadlock:
x and y are shared variables and syncA and syncB may be acquired by any other thread. But with the following code, there is no deadlock possible.
/* 1 */ synchronized(syncA) {
/* 2 */ x = 1;
/* 3 */ }
/* 4 */ y = 0;
/* 5 */ synchronized(syncB) {
/* 6 */ y = 1;
/* 7 */ }
If, however, the acquire of syncA is reordered into the syncB block this might cause a deadlock:
y = 0;
synchronized(syncB) {
y = 1;
synchronized(syncA) {
x = 1;
}
}
I think this is not a legal compiler transformation, because it would change the synchronization order. Am I right with this assumption? What part of the Java Memory Model (JMM) allows/disallows this?
Thanks to assylias for linking to this question which contains an answer with this image from the JSR-133 Cookbook:
According to this image the compiler transformation from EDIT 3 is illegal, because it reorders two MonitorEnters.
Also, this table shows which synchronization-edges are what kinds of "reordering-barriers" for which other operations.
Thank you for your help :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With