每当在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


当前回答

不,你不应该总是这样。但是,当一个特定对象上有多个关注点时,我倾向于避免它,而这些关注点只需要对它们本身是线程安全的。例如,你可能有一个可变数据对象,它有“label”和“parent”字段;它们需要是线程安全的,但是改变其中一个不需要阻止另一个被写入/读取。(在实践中,我将通过声明字段为volatile和/或使用java.util来避免这种情况。concurrent的AtomicFoo包装器)。

一般来说,同步有点笨拙,因为它只是一个大的锁定,而不是仔细考虑如何允许线程相互工作。使用synchronized(this)更加笨拙和反社会,因为它表示“当我持有锁时,没有人可以更改这个类的任何内容”。你需要多久做一次?

I would much rather have more granular locks; even if you do want to stop everything from changing (perhaps you're serialising the object), you can just acquire all of the locks to achieve the same thing, plus it's more explicit that way. When you use synchronized(this), it's not clear exactly why you're synchronizing, or what the side effects might be. If you use synchronized(labelMonitor), or even better labelLock.getWriteLock().lock(), it's clear what you are doing and what the effects of your critical section are limited to.

其他回答

在c#和Java阵营中似乎有不同的共识。我看到的大多数Java代码使用:

// apply mutex to this instance
synchronized(this) {
    // do work here
}

而大多数c#代码选择了更安全的:

// instance level lock object
private readonly object _syncObj = new object();

...

// apply mutex to private instance level field (a System.Object usually)
lock(_syncObj)
{
    // do work here
}

c#语言当然更安全。如前所述,不能从实例外部对锁进行恶意/意外访问。Java代码也有这种风险,但随着时间的推移,Java社区似乎倾向于稍微不那么安全,但稍微更简洁的版本。

这并不是对Java的挖苦,只是我在这两种语言上工作的经验的反映。

我将分别讨论每一点。

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.

当您使用synchronized(this)时,您正在使用类实例作为锁本身。这意味着当线程1获得锁时,线程2应该等待。

假设有以下代码:

public void method1() {
    // do something ...
    synchronized(this) {
        a ++;      
    }
    // ................
}


public void method2() {
    // do something ...
    synchronized(this) {
        b ++;      
    }
    // ................
}

方法一修改变量a,方法二修改变量b,应避免两个线程同时修改同一个变量。但是当thread1修改a和thread2修改b时,它可以在没有任何竞争条件的情况下执行。

不幸的是,上面的代码不允许这样做,因为我们对锁使用了相同的引用;这意味着线程即使没有处于竞争状态也应该等待,显然代码牺牲了程序的并发性。

解决方案是对两个不同的变量使用两个不同的锁:

public class Test {

    private Object lockA = new Object();
    private Object lockB = new Object();

    public void method1() {
        // do something ...
        synchronized(lockA) {
            a ++;      
        }
        // ................
    }


    public void method2() {
        // do something ...
        synchronized(lockB) {
            b ++;      
        }
        // ................
    }

}

上面的例子使用了更细粒度的锁(2个锁而不是一个锁(分别针对变量a和变量b的lockA和lockB),结果允许更好的并发性,另一方面,它变得比第一个例子更复杂……

简单的回答:您必须了解其中的区别,并根据代码做出选择。

Long answer: In general I would rather try to avoid synchronize(this) to reduce contention but private locks add complexity you have to be aware of. So use the right synchronization for the right job. If you are not so experienced with multi-threaded programming I would rather stick to instance locking and read up on this topic. (That said: just using synchronize(this) does not automatically make your class fully thread-safe.) This is a not an easy topic but once you get used to it, the answer whether to use synchronize(this) or not comes naturally.

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

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

编译,

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

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