4

If I have a synchronized block and somewhere inside that block an exception is thrown that is not caught within the synchronized block, would the lock be relinquished when the exception propagates out of it?(the synchronized block)

synchronized( mutex )
{
    throw new Exception( "" );
}
shawn
  • 4,063
  • 7
  • 37
  • 54
  • 1
    possible duplicate of [Side effects of throwing an exception inside a synchronized clause?](http://stackoverflow.com/questions/2019339/side-effects-of-throwing-an-exception-inside-a-synchronized-clause) – Mat Dec 04 '11 at 12:08

3 Answers3

7

The lock is always released.

From JLS §14.19:

"If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason."

oligofren
  • 20,744
  • 16
  • 93
  • 180
3

Yes, the lock is released.

From here:

The exception mechanism of the Java platform is integrated with its synchronization model (§17), so that locks are released as synchronized statements (§14.18) and invocations of synchronized methods (§8.4.3.6, §15.12) complete abruptly.

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

There should be no problem. The lock is released whatever the execution path is (return, exception...) See this for details.

Community
  • 1
  • 1
GETah
  • 20,922
  • 7
  • 61
  • 103