我只是想知道在新的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
在新的JMM模型下,以上四种情况都是对原始代码的有效重新排序吗?我已经基于我对http://gee.cs.oswego.edu/dl/jmm/cookbook.html的理解给出了以上所有的重新排序
1条答案
按热度按时间kxkpmulp1#
考虑如何在监视器进入和退出时对正常加载/存储进行重新排序:
情况1使用监视器进入对正常加载/存储进行重新排序,这是有效的重新排序。
情况2使用监视器进入和监视器退出对正常加载/存储进行重新排序,监视器退出之后是正常加载/存储,这些都是有效的重新排序。
请看类似的例子:Roach Motels and Java Memory Model。这表明可以将访问移入同步块,但不能再次移出。
情况3和4重新排序监视器进入,然后是无效的正常加载/存储。