问题描述
众所周知,JVM不应将带有synchronized块的语句重新排序到synchronized块之外。考虑到这一点,JVM是否允许在以下代码段中的 synchronized
块之后重新排序分配 y = 7
?
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;
}
有人可能会说,因为这是有效的订购, y
在 synchronized
块之后不能进行赋值,因为它违反了同步块内的代码不得重新排序后发生的规则阻止并推断 y
在同步块的结束之前发生。
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.
另一方面,可能所有的订单都不相同,而且实际订购的顺序也很重要。具体来说,如果 y
赋值最初是在同步块内完成的,那么在块之后就不会发生,否则就可能发生。
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;
推荐答案
:
...
- 如果动作x同步 - 以下操作y,那么我们也有hb(x,y)。
你的在包含假设 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.
这篇关于java中的同步重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!