且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中避免同步(这个)?

更新时间:2023-10-05 15:15:52

我将分别介绍每一点.

一些邪恶的代码可能会偷你的锁(这个很流行,还有一个意外"变体)

Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)

我更担心意外.它的意思是 this 的这种使用是您的类公开接口的一部分,应该记录下来.有时需要其他代码使用您的锁的能力.Collections.synchronizedMap 之类的东西也是如此(请参阅 javadoc).

I'm more worried about accidentally. What it amounts to is that this use of this is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like Collections.synchronizedMap (see the javadoc).

同一类中的所有同步方法都使用完全相同的锁,降低吞吐量

All synchronized methods within the same class use the exact same lock, which reduces throughput

这是过于简单化的想法;仅仅去掉 synchronized(this) 并不能解决问题.吞吐量的适当同步需要更多考虑.

This is overly simplistic thinking; just getting rid of synchronized(this) won't solve the problem. Proper synchronization for throughput will take more thought.

你(不必要地)暴露了太多信息

You are (unnecessarily) exposing too much information

这是#1 的变体.synchronized(this) 的使用是界面的一部分.如果你不想/不需要暴露这个,就不要这样做.

This is a variant of #1. Use of synchronized(this) is part of your interface. If you don't want/need this exposed, don't do it.