`
奋斗的西瓜
  • 浏览: 970 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Java Concurrency in Practice疑问

阅读更多
最近在拜读Java Concurrency in Practice
有一处不理解的地方,还请群里的大牛们不吝赐教~
Reentrancy facilitates encapsulation of locking behavior, and thus simplifies the development of object-oriented concurrent code. Without reentrant locks, the very natural-looking code in Listing 2.7, in which a subclass overrides a synchronized method and then calls the superclass method, would deadlock. Because the doSomething methods in Widget and LoggingWidget are both synchronized, each tries to acquire the lock on the Widget before proceeding. But if intrinsic locks were not reentrant, the call to super.doSomething would never be able to acquire the lock because it would be considered already held, and the thread would permanently stall waiting for a lock it can never acquire.
翻译过来大致是这样的:
可重入性封装了获取锁的行为,并且也简化了面向对象式并发代码的开发。如果没有可重入性,2.7中很自然的代码(子类重写了父类的同步方法,并且在重写后的方法内又调用了父类的这一同步方法)将会造成死锁。因为,Widget类和LoggingWidget类中的doSomething方法都是同步的,他们各自在处理前都尝试去获取Widget的锁。但是如果锁不是可重入的,那么super.doSomething这段代码将永远不能获取锁,因为这个锁被认为已经持有了,于是这个线程将永久的等待一个不可能获取得到的锁。
Listing 2.7
public class Widget {
    public synchronized void doSomething() {
        ...
    }
}
public class LoggingWidget extends Widget {
    public synchronized void doSomething() {
        System.out.println(toString() + ": calling doSomething");
        super.doSomething();
    }
}

问题:(红线部分)
1.当调用LoggingWidget的doSomething方法时,如果没有可重入性,获取锁的步骤的怎样的,为什么会死锁?LoggingWidget对象的锁和Widget的锁有什么关系?
2.第二段红线部分,“这个锁被认为已经持有了”,是被谁持有了?是当前获取了LoggingWidget对象锁的这一线程吗?
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics