是否由Java编译器优化了空的同步块? [英] Are empty synchronized blocks optimized out by Java compiler?

查看:130
本文介绍了是否由Java编译器优化了空的同步块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在我的代码中某处我写了一个空的 synchronized 块:

Suppose somewhere in my code I write an empty synchronized block:

synchronized(obj){
   //No code here
}

因为synchronized块不包含任何代码,JIT编译器是否会通过不锁定 obj 来优化它,因为它没用?

So as the synchronized block does not contain any code, will JIT compiler optimize that out by not locking on obj as it will be of no use?

Java编译器做类似的技巧,比如锁定粗化,但这个同步块也会被优化掉吗?

Java compiler does similar tricks such as Lock coarsening but will this synchronized block be also optimized out?

编辑:

根据assylias的观点,

As per the point made by assylias,

synchronized(new Object()){
   //empty block
}

将JIT编译器现在能够优化它,因为我使用的是一个不能逃避我的方法的对象吗?

will the JIT compiler now be able to optimize this out, since I am using an Object which doesn't escape my method?

推荐答案

这个无法在Java Memory Model语义的基础上进行优化。锁定获取 - 释放操作可以替换为其他内容,但即使是空的 synchronized 块也会影响其他线程采取的操作的可见性获取相同的锁。

This can't be optimized away on the basis of the Java Memory Model semantics. The lock acquisition-release operation may be replaced by something else, but even an empty synchronized block has consequences on the visibility of actions taken by other threads acquiring the same lock.

具体来说,保证在发布锁之前由一个线程完成的所有写操作在获取后对另一个线程可见相同的锁

这是一个非常不同的案例:一个锁在一个对象上获得,该对象可以通过逃逸分析证明没有其他线程能够获取它。在这种情况下, synchronized 块的内容无关紧要:该点仅在使用的锁中。代码可以看起来像你发布它,或者甚至像这样:

This is a very different case: a lock is obtained on an object which can be proved by escape analysis that no other thread will ever be able to fetch it. In this case it doesn't matter what the contents of the synchronized block are: the point is only in the lock used. The code can look as you posted it, or even like this:

Object o = new Object();
synchronized(o) { 
   // any operations you like, as long as they don't let o escape the method scope
}

这可以通过称为 lock elision 的转换来执行:JVM可以假装它从未见过 synchronized 块。这是因为JMM语义仅指获取同一个锁的情况。

This can be acted upon by the transformation known as lock elision: the JVM can pretend it never saw the synchronized block. This is because the JMM semantics refer only to the cases of acquiring the one and the same lock.

这篇关于是否由Java编译器优化了空的同步块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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