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


当前回答

这要视情况而定。 如果只有一个或多个共享实体。

在这里查看完整的工作示例

简单介绍一下。

线程和可共享实体 多个线程可以访问同一个实体,例如多个connectionThreads共享一个messageQueue。由于线程并发运行,可能会有一个数据被另一个覆盖的机会,这可能是一个混乱的情况。 因此,我们需要某种方法来确保可共享实体一次只能被一个线程访问。(并发)。

同步块 Synchronized()块是一种确保可共享实体并发访问的方法。 首先,打个小比方 假设有两个人P1, P2(线程)一个盥洗室(可共享实体),有一扇门(锁)。 现在我们想让一个人一次使用脸盆。 一种方法是在P1锁门的时候P2等待P1完成他的工作 P1打开门 那么只有p1可以使用脸盆。

语法。

synchronized(this)
{
  SHARED_ENTITY.....
}

"this" provided the intrinsic lock associated with the class (Java developer designed Object class in such a way that each object can work as monitor). Above approach works fine when there are only one shared entity and multiple threads (1: N). N shareable entities-M threads Now think of a situation when there is two washbasin inside a washroom and only one door. If we are using the previous approach, only p1 can use one washbasin at a time while p2 will wait outside. It is wastage of resource as no one is using B2 (washbasin). A wiser approach would be to create a smaller room inside washroom and provide them one door per washbasin. In this way, P1 can access B1 and P2 can access B2 and vice-versa.

washbasin1;  
washbasin2;

Object lock1=new Object();
Object lock2=new Object();

  synchronized(lock1)
  {
    washbasin1;
  }

  synchronized(lock2)
  {
    washbasin2;
  }


在这里查看更多关于Threads---->的信息

其他回答

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

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

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

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

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

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

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

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

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

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

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

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

在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的挖苦,只是我在这两种语言上工作的经验的反映。

I think there is a good explanation on why each of these are vital techniques under your belt in a book called Java Concurrency In Practice by Brian Goetz. He makes one point very clear - you must use the same lock "EVERYWHERE" to protect the state of your object. Synchronised method and synchronising on an object often go hand in hand. E.g. Vector synchronises all its methods. If you have a handle to a vector object and are going to do "put if absent" then merely Vector synchronising its own individual methods isn't going to protect you from corruption of state. You need to synchronise using synchronised (vectorHandle). This will result in the SAME lock being acquired by every thread which has a handle to the vector and will protect overall state of the vector. This is called client side locking. We do know as a matter of fact vector does synchronised (this) / synchronises all its methods and hence synchronising on the object vectorHandle will result in proper synchronisation of vector objects state. Its foolish to believe that you are thread safe just because you are using a thread safe collection. This is precisely the reason ConcurrentHashMap explicitly introduced putIfAbsent method - to make such operations atomic.

总之

Synchronising at method level allows client side locking. If you have a private lock object - it makes client side locking impossible. This is fine if you know that your class doesn't have "put if absent" type of functionality. If you are designing a library - then synchronising on this or synchronising the method is often wiser. Because you are rarely in a position to decide how your class is going to be used. Had Vector used a private lock object - it would have been impossible to get "put if absent" right. The client code will never gain a handle to the private lock thus breaking the fundamental rule of using the EXACT SAME LOCK to protect its state. Synchronising on this or synchronised methods do have a problem as others have pointed out - someone could get a lock and never release it. All other threads would keep waiting for the lock to be released. So know what you are doing and adopt the one that's correct. Someone argued that having a private lock object gives you better granularity - e.g. if two operations are unrelated - they could be guarded by different locks resulting in better throughput. But this i think is design smell and not code smell - if two operations are completely unrelated why are they part of the SAME class? Why should a class club unrelated functionalities at all? May be a utility class? Hmmmm - some util providing string manipulation and calendar date formatting through the same instance?? ... doesn't make any sense to me at least!!

避免使用synchronized(this)作为锁定机制:这会锁定整个类实例,并可能导致死锁。在这种情况下,重构代码以只锁定特定的方法或变量,这样整个类就不会被锁定。同步可以在方法级别内使用。 下面的代码展示了如何锁定一个方法,而不是使用synchronized(this)。

   public void foo() {
if(operation = null) {
    synchronized(foo) { 
if (operation == null) {
 // enter your code that this method has to handle...
          }
        }
      }
    }