Synchronized reordering in java

牧云@^-^@ 提交于 2019-12-06 05:52:33

问题


It is known that JVM shouldn't reorder statements from withing synchronized block to outside of the synchronized block. Considering this, is JVM allowed to reorder assignment y = 7 to occur after the synchronized block in the following snippet?

x = 5;
y = 7;
synchronized (this) {
    x = 6;
}

We know that variable assignment before the synchronized block can be reordered to occur inside the block. So the following should be valid reordering of the initial code:

x = 5;
synchronized (this) {
    x = 6;
    y = 7;
}

One could argue that, because this is a valid ordering, y assignment cannot occur after the synchronized block as it would violate the rule that code from within synchronized block mustn't be reordered to occur after the block and deduce that y happens-before end of the synchronized block.

On the other hand, it could be that all orderings are not equivalent and it matters which ordering was the actual ordering. Specifically, if y assignment was originally done within the synchronized block it couldn't occur after the block, otherwise it could.

To sum up, is next ordering valid ordering of the first snippet?

x = 5;
synchronized (this) {
    x = 6;
}
y = 7;

回答1:


JLS 17.4.5:

  • If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

...

  • If an action x synchronizes-with a following action y, then we also have hb(x, y).

Your question only makes sense when including the assumption that the value of y could be visible outside the current thread. If that's the case, the combination of these two rules requires that the assignment not be reordered after the synchronized block.




回答2:


Yes, your reasoning are flawed; this can not happen.

A monitor enter is like a volatile load (not entirely correct, but I understand it simpler like that - there will be two barriers inserted : LoadLoad|LoadStore) and operations that are before that can not float across that barrier.

I am pretty sure, this is specified by the JLS and while I wanted to link to that, the other answer has already did - go upvote it.



来源:https://stackoverflow.com/questions/52806674/synchronized-reordering-in-java

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