Java:嵌套同步块 [英] Java: Nested synchronization blocks

查看:555
本文介绍了Java:嵌套同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Heinz Kabutz的 Java专家时事通讯版本中看到这一点,虽然Kabutz博士的文章的其余部分(甚至全部)都有很好的解释和详细描述,这个代码在做什么,或更重要的是,它的意义是:

I saw this in one of Heinz Kabutz's Java Specialist newsletter editions and, although the rest (and indeed, all) of Dr. Kabutz's articles are well-explained and detailed, he seemed to gloss over what this code is doing, or more importantly, what it's significance is:

public class SomeObject {
    private Object lock1;
    private Object lock2;

    public void doSomething() {
        synchronized(lock1) {
            synchronized(lock2) {
                // ...
            }
        }
    }
}

嵌套的影响 syncrhonized 块?这如何影响尝试 doSomething()

What are the implications of nesting syncrhonized blocks? How does this affect different threads attempting to doSomething()?

推荐答案

有两个可能的问题,一个人必须注意

There are 2 possible issues that one would have to watch out for


  1. 嵌套锁可能会导致死锁很容易,如果一个使用等待/通知。这里是为什么的解释。 http://tutorials.jenkov.com/java-concurrency/nested-monitor-lockout.html

请注意,如果另一个方法希望锁定相同的两个对象,它们必须始终以相同的顺序执行,否则如本文中所述的另一种死锁情况的可能性:如何避免嵌套同步和导致的死锁

One should be wary that if another method wishes to lock the same two objects, they must always do it in the same order, otherwise there is the possibility of another deadlock situation as explained in this post: How to avoid Nested synchronization and the resulting deadlock

这篇关于Java:嵌套同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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