我只是想知道下面的重新排序是否有效,在新的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
解决方法:
考虑如何在监视器进入和退出时重新排序正常加载/存储:
案例1使用监视器输入重新排序正常加载/存储,这是有效的重新排序.
案例2使用监视器输入重新排序正常加载/存储,然后是监视器出口,然后是正常加载/存储,这是有效的重新排序.
请参阅类似的示例:Roach Motels and Java Memory Model.这表明访问可以移动到同步块中,但不能再次退出.
情况3和4重新排序监视器,然后是正常的加载/存储,这是无效的.