每当在SO上出现关于Java同步的问题时,有些人都急于指出应该避免同步(这一点)。相反,他们声称,对私有引用的锁定是首选的。

其中一些原因是:

一些邪恶的代码可能会偷你的锁(这个很流行,也有一个“意外”变体) 同一类中的所有同步方法都使用完全相同的锁,这降低了吞吐量 你(不必要地)暴露了太多信息

包括我在内的其他人认为,synchronized(this)是一个被大量使用的习语(在Java库中也是如此),是安全的,而且很容易理解。它不应该被避免,因为你有一个错误,你不知道你的多线程程序中发生了什么。换句话说:如果它是适用的,那么就使用它。

我感兴趣的是看到一些现实世界的例子(没有foobar的东西),避免锁定在这是可取的,当同步(这)也会做的工作。

因此:您应该总是避免synchronized(this),并将其替换为私有引用上的锁吗?


一些进一步的信息(随着答案的更新):

we are talking about instance synchronization both implicit (synchronized methods) and explicit form of synchronized(this) are considered if you quote Bloch or other authorities on the subject, don't leave out the parts you don't like (e.g. Effective Java, item on Thread Safety: Typically it is the lock on the instance itself, but there are exceptions.) if you need granularity in your locking other than synchronized(this) provides, then synchronized(this) is not applicable so that's not the issue


当前回答

我对2019年的看法,尽管这个问题本可以已经解决了。

如果你知道你在做什么,锁定'this'并不坏,但在幕后锁定'this'是(不幸的是synchronized关键字在方法定义中允许)。

如果你真的希望你的类的用户能够“窃取”你的锁(即阻止其他线程处理它),你实际上希望所有同步方法在另一个同步方法运行时等待,以此类推。 它应该是有意的、经过深思熟虑的(因此有文档来帮助用户理解它)。

更详细地说,反过来,你必须知道如果你锁定了一个不可访问的锁(没有人可以“偷”你的锁,你完全控制等等),你会“获得”(或“失去”)什么。

对我来说,问题是方法定义签名中的synchronized关键字使程序员很容易不考虑锁定什么,如果你不想在多线程程序中遇到问题,这是一个非常重要的事情。

人们不能争辩说,“通常”你不希望你的类的用户能够做这些事情,或者“通常”你想要……这取决于你编写的是什么功能。因为你不能预测所有的用例,所以你不能制定一个经验法则。

例如,prinwriter使用了一个内部锁,但是如果人们不想让他们的输出相互交错,他们就很难从多个线程中使用它。

锁是否可以在类外部访问是程序员根据类的功能来决定的。它是api的一部分。例如,你不能从synchronized(this)移到synchronized(provateObjet)而不冒破坏使用它的代码更改的风险。

注1:我知道你可以实现任何同步(这个)'实现'通过使用显式锁对象和暴露它,但我认为这是不必要的,如果你的行为是很好的记录,你实际上知道什么锁定'this'的意思。

注2:我不同意这样的观点:如果一些代码不小心偷了你的锁,那就是一个bug,你必须解决它。这在某种程度上等同于说我可以让我所有的方法公开,即使它们本不应该是公开的。如果有人“意外”调用我的意图是私人方法,这是一个bug。为什么会发生这样的事故!!如果能偷你的锁对你的类来说是一个问题,那就不要允许它。就这么简单。

其他回答

concurrent包极大地降低了线程安全代码的复杂性。我只有一些轶事证据,但我所见过的大多数synchronized(x)工作似乎都是重新实现Lock、Semaphore或Latch,但使用的是较低级别的监视器。

考虑到这一点,使用这些机制中的任何一种进行同步都类似于对内部对象进行同步,而不是泄露锁。这是非常有益的,因为您可以绝对确定通过两个或多个线程控制进入监视器的条目。

我将分别讨论每一点。

Some evil code may steal your lock (very popular this one, also has an "accidentally" variant) 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 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 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.

我认为第一点(其他人使用您的锁)和第二点(所有方法不必要地使用相同的锁)可能发生在任何相当大的应用程序中。特别是当开发人员之间没有良好的沟通时。

这不是一成不变的,这主要是一个良好的实践和防止错误的问题。

这实际上只是对其他答案的补充,但如果你对使用私有对象进行锁定的主要反对意见是,它会使你的类与与业务逻辑无关的字段混乱,那么Project Lombok有@Synchronized在编译时生成样板:

@Synchronized
public int foo() {
    return 0;
}

编译,

private final Object $lock = new Object[0];

public int foo() {
    synchronized($lock) {
        return 0;
    }
}

如果可能的话,让你的数据不可变(最终变量) 如果你不能避免跨多个线程共享数据的突变,使用高级编程结构[例如,粒度锁API]

Lock提供对共享资源的独占访问:一次只有一个线程可以获得锁,并且对共享资源的所有访问都要求首先获得锁。

使用ReentrantLock实现Lock接口的示例代码

 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

锁定相对于同步的优势

The use of synchronized methods or statements forces all lock acquisition and release to occur in a block-structured way. Lock implementations provide additional functionality over the use of synchronized methods and statements by providing A non-blocking attempt to acquire a lock (tryLock()) An attempt to acquire the lock that can be interrupted (lockInterruptibly()) An attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)). A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering non-re entrant usage Deadlock detection

看看这个关于各种锁的SE问题:

同步vs锁定

您可以通过使用高级并发API而不是synchronized块来实现线程安全。该文档页提供了实现线程安全的良好编程结构。

锁对象支持简化许多并发应用程序的锁定习惯用法。

executor为启动和管理线程定义了高级API。concurrent提供的执行器实现提供了适合大型应用程序的线程池管理。

并发集合使管理大型数据集合变得更容易,并且可以大大减少同步的需要。

原子变量具有最小化同步和帮助避免内存一致性错误的特性。

ThreadLocalRandom(在JDK 7中)提供了从多个线程有效生成伪随机数的功能。

其他编程结构也可以参考java.util.concurrent和java.util.concurrent.atomic包。