Martin08
Martin08

Reputation: 21450

will deadlock occur in these situations?

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.

Upvotes: 1

Views: 396

Answers (3)

Michael Schmeißer
Michael Schmeißer

Reputation: 3417

  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.

Upvotes: 1

Tim Pote
Tim Pote

Reputation: 28049

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.

Upvotes: 0

TacticalCoder
TacticalCoder

Reputation: 6325

  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?

Upvotes: 2

Related Questions