Does a Deadlock Occur in This Case?

半世苍凉 提交于 2019-12-22 18:15:43

问题


Am I right in saying that a deadlock is supposed to happen in the following case:

Object P calls a synch method of object A,
that calls a synch method of object B,
that calls a synch method of object A.

Sorry if it looks stupid of me, most probably it is. But that's why I'm asking. Thanks!


回答1:


By the information you give - no, a deadlock can't occur:

First, you don't mention multiple threads. A single thread can't cause a deadlock. But let's assume you have multiple threads.

So, if any other object, from different thread invokes some of these methods in reverse order, then a deadlock can occur.

The explanation of the situation is as follows: Thread-1 obtains the lock required to enter methodA, and then tries to enter methodB. If at the same moment another thread - Thread-2 invokes methodB and obtains the lock for it, then tries to enter methodA, but Thread-1 already has the lock, so Thread-2 waits. However, Thread-1 can't enter methodB because Thread-2 has the lock. And they wait forever (deadlock).




回答2:


No. It is same thread, synch methods are reenterable.

If you take definition from wikipedia: "A deadlock is a situation wherein two or more competing actions are each waiting for the other to finish". You have only one action (thread) .




回答3:


No, the thread will already hold the lock on A, so it won't deadlock. A thread can never contend for a lock with itself.



来源:https://stackoverflow.com/questions/3679736/does-a-deadlock-occur-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!