众所周知,JVM 不应将同步块(synchronized block)内的语句重新排序到同步块(synchronized block)外。考虑到这一点,是否允许 JVM 重新排序分配 y = 7
以在以下代码段中的 synchronized
block 之后发生?
x = 5;
y = 7;
synchronized (this) {
x = 6;
}
我们知道同步块(synchronized block)之前的变量赋值可以重新排序发生在 block 内。因此,以下应该是初始代码的有效重新排序:
x = 5;
synchronized (this) {
x = 6;
y = 7;
}
有人可能会争辩说,因为这是一个有效的顺序,y
赋值不能发生在 synchronized
block 之后,因为它会违反 synchronized block 中的代码必须't 被重新排序为在 block 之后发生并推断 y
happens-before end 同步块(synchronized block)。
另一方面,可能并非所有顺序都是等价的,哪个顺序是实际顺序很重要。具体来说,如果 y
赋值最初是在同步块(synchronized block)内完成的,那么它就不会在该 block 之后发生,否则就可能发生。
总而言之,next ordering 是否是第一个片段的有效排序?
x = 5;
synchronized (this) {
x = 6;
}
y = 7;
最佳答案
- 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).
只有在假设 y
的值在当前线程外可见时,您的问题才有意义。如果是这种情况,这两个规则的组合要求在同步块(synchronized block)之后不重新排序赋值。
关于java - java中的同步重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52806674/