Does a Deadlock Occur in This Case?

2019-05-23 01:12发布

问题:

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.