问题描述
可以重新排序同步语句。即:
可以:
Can the synchronization statements be reordered. i.e :Can :
synchronized(A) {
synchronized(B) {
......
}
}
成为:
synchronized(B) {
synchronized(A) {
......
}
}
推荐答案
我假设您在询问编译器是否可以重新排序 synchronized
阻止所以锁定顺序的顺序与代码不同。
I assume you are asking if the compiler can reorder the synchronized
blocks so the lock order happens in a different order than the code.
答案是否定的。 synchronized
块(以及 volatile
字段访问权限)对编译器施加了排序限制。在您的情况下,您无法在另一个监视器输入之前移动监视器 - 输入,也不能在另一个监视器退出之后移动监视器退出。请参阅下面的网格。
The answer is no. A synchronized
block (and a volatile
field access) impose ordering restrictions on the compiler. In your case, you cannot move a monitor-enter before another monitor-enter nor a monitor-exit after another monitor-exit. See the grid below.
引用:
Doug Lea的有一个网格,显示重新排序的可能性。网格中的空白条目表示允许重新排序。在您的情况下,输入 synchronized
块是MonitorEnter(与加载 volatile
字段相同的重新排序限制)退出 synchronized
块是一个MonitorExit(与存储到 volatile
字段相同)。
Doug Lea's JSR-133 Cookbook has a grid which shows the reordering possibilities. A blank entry in the grid means that reordering is allowed. In your case, entering a synchronized
block is a "MonitorEnter" (same reordering limitations as loading of a volatile
field) and exiting a synchronized
block is a "MonitorExit" (same as storing to a volatile
field).
这篇关于Java编译器可以重新排序synchronized语句以进行优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!