我只是想知道下面的重新排序是否有效,在新的JMM模型
下Original Code:
instanceVar1 = value ;// normal read operation, no volatile
synchronized(this) {
instanceVar2 = value2; //normal read operation, no volatile
}
instanceVar3 = value3; //normal read operation, no volatile
以上代码可以重新排序到以下执行中。
Case 1:
synchronized(this) {
instanceVar2 = value2; //normal read operation, no volatile
instanceVar1 = value ;// normal read operation, no volatile
}
instanceVar3 = value3; //normal read operation, no volatile
另一个案例:
Case 2:
synchronized(this) {
instanceVar3 = value3; //normal read operation, no volatile
instanceVar2 = value2; //normal read operation, no volatile
instanceVar1 = value ;// normal read operation, no volatile
}
另一个案例:
Case 3:
instanceVar3 = value3; //normal read operation, no volatile
synchronized(this) {
instanceVar2 = value2; //normal read operation, no volatile
instanceVar1 = value ;// normal read operation, no volatile
}
另一个案例:
Case 4:
instanceVar3 = value3; //normal read operation, no volatile
synchronized(this) {
instanceVar2 = value2; //normal read operation, no volatile
}
instanceVar1 = value ;// normal read operation, no volatile
以上4种情况都是新JMM模型下原始代码的有效重新排序。 根据我的理解,我已经给出了上述所有重新排序 http://gee.cs.oswego.edu/dl/jmm/cookbook.html
答案 0 :(得分:1)
考虑如何使用监视器进入和退出重新排序正常加载/存储:
案例1使用监视器输入重新排序正常加载/存储,这是有效的重新排序。
案例2重新排序正常的加载/存储,监视器输入,监视器退出,然后是正常加载/存储,这是有效的重新排序。
查看类似示例:Roach Motels and Java Memory Model。这表明访问可以移动到同步块中,但不能再次退出。
案例3和4重新排序显示器,然后输入无效的正常加载/存储。