每当出现关于Java同步的问题时,一些人都会非常Eager 地指出,应该避免synchronized(this)
个.相反,他们声称,最好是锁定私有引用.
其中一些原因是:
- some evil code may steal your lock(这款非常流行,还有一个"意外"变体)
- all synchronized methods within the same class use the exact same lock, which reduces throughput个
- you are (unnecessarily) exposing too much information
包括我在内的其他人认为,synchronized(this)
是一个经常使用的习惯用法(也在Java库中使用),它是安全的,并且易于理解.它不应该被避免,因为你有一个bug,你不知道你的多线程程序中发生了什么.换句话说:如果它适用,那么就使用它.
我感兴趣的是看到一些现实世界的例子(没有foobar的东西),当synchronized(this)
也可以做这项工作时,避免锁定this
是更可取的.
因此:should you always avoid 100 and replace it with a lock on a private reference?
更多信息(随答案更新):
- 我们正在讨论实例同步
- 同时考虑了隐式(
synchronized
种方法)和显式形式的synchronized(this)
- 如果你引用布洛赫或其他权威人士的话,不要遗漏你不喜欢的部分(例如,有效Java,线程安全项目:Typically it is the lock on the instance itself, but there are exceptions.))
- 如果在锁定中需要
synchronized(this)
以外的粒度,那么synchronized(this)
不适用,所以这不是问题所在