views:

83

answers:

3

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!

+2  A: 

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) .

Andrey
+2  A: 

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.

erickson
Actually, this is only true for re-entrant locks. In java, synchronized blocks do indeed use re-entrant locks, so you are OK.
Bill Michell
+8  A: 

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).

Bozho