1

will deadlock occur in these Java situations
1-

synchronized(obj) {
   obj.syncMethod(); // the method signature: public synchronized void syncMethod() {...}
}

2-

synchronized(obj) {
  if (condition) 
     throw new Exception(); // deadlock because obj lock is not released?
  // do other stuff
}

Thank you.

Martin08
  • 20,990
  • 22
  • 84
  • 93
  • I have no experience with synchronised methods, but it would seem silly that deadlocks can occur just because an Exception is thrown and the execution of the method is thus terminated abnormally. And, if that was the case, you could catch any exception there, unlock the object, and throw a new exception. – MarioDS Apr 11 '12 at 23:01
  • Why don't you test your code and find out? – Shawn Shroyer Apr 12 '12 at 00:54

3 Answers3

2
  1. No deadlock shall occur. You're already holding the lock to obj.

  2. If an exception is thrown the lock is released. See the question here on SO:

Side effects of throwing an exception inside a synchronized clause?

Community
  • 1
  • 1
TacticalCoder
  • 6,275
  • 3
  • 31
  • 39
1
  1. No deadlock will occur - Java's locks are reentrant, that is, while a thread is holding a lock (in your case on obj) it can enter synchronized blocks requiring the same lock without problem (a synchronized method is synchronized on this, which is obj in your case too).
  2. The lock will be released when the synchronized block is left, no matter whether an exception causes the thread to leave it or not.
Michael Schmeißer
  • 3,407
  • 1
  • 19
  • 32
  • That why when using j.u.c.Locks a best practice is to perform locking/unlocking in a try/finally block - to ensure always that unlocking is performed. Intrinsic syncronization (aka syncronized) offers this by default - but has other limitations – Ovidiu Lupas Apr 20 '12 at 11:15
0

If you don't catch the exception in your synchronized block, then your lock will be released and no deadlock can occur. See here for details.

Tim Pote
  • 27,191
  • 6
  • 63
  • 65