Java编译器可以重新排序synchronized语句以进行优化吗? [英] Can the synchronized statements be re-ordered by Java compiler for optimization?

查看:186
本文介绍了Java编译器可以重新排序synchronized语句以进行优化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以重新排序同步语句。即:
可以:

Can the synchronization statements be reordered. i.e : Can :

synchronized(A) {
   synchronized(B) {
     ......
   }
}

成为:

synchronized(B) { 
    synchronized(A) { 
     ...... 
     }  
}


推荐答案


可以重新排序同步语句吗?

Can the synchronization statements be reordered?

我假设您在询问编译器是否可以重新排序 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.

引用 JSR 133(Java内存模型)常见问题解答


它例如,编译器无法在获取之前或发布之后移动代码。当我们说获取和释放对缓存有效时,我们使用速记来表示一些可能的效果。

It is not possible, for example, for the compiler to move your code before an acquire or after a release. When we say that acquires and releases act on caches, we are using shorthand for a number of possible effects.

Doug Lea的 JSR-133 Cookbook 有一个网格,显示重新排序的可能性。网格中的空白条目表示允许重新排序。在您的情况下,输入 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语句以进行优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆