同步方法以递归方式调用自身。这打破了吗? [英] Synchronized method calls itself recursively. Is this broken?

查看:262
本文介绍了同步方法以递归方式调用自身。这打破了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的关键在于说明Java没有像我预期的那样工作。

The point of this question is to illustrate that Java is not working as I expected.

您希望以下代码表现如何?

How would you expect the following code to behave?

public class SynchTester {
  private static SynchTester synchTester;

  public synchronized static SynchTester getSynchTester(){
    if(synchTester==null){
      synchTester = new SynchTester();
    }

    return synchTester;
  }

  private SynchTester() {
    SynchTester myTester = getSynchTester();
  }

  public static void main(String[] args) {
    SynchTester tester = SynchTester.getSynchTester();
  }
}

我希望它会挂起,等待死锁递归完成,但它抛出StackOverflow。明显同步不会阻止访问同一个线程。

I would expect it to hang with a deadlock waiting on the recursion to complete, but instead it throws StackOverflow. Evidently synchronized does not block access to the same thread.

这是一个错误吗?

推荐答案

在Java中,同步锁是可重入

In Java, synchronized locks are reentrant.


回想一下,线程无法获取另一个线程拥有的锁。 但线程可以获得已拥有的锁。允许线程多次获取相同的锁可启用重入同步。这描述了一种情况,其中同步代码直接或间接地调用也包含同步代码的方法,并且两组代码使用相同的锁。在没有可重入同步的情况下,同步代码必须采取许多额外的预防措施,以避免线程导致自身阻塞。

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

来源:见此页面

这篇关于同步方法以递归方式调用自身。这打破了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆