Side effects of throwing an exception inside a synchronized clause?

JavaExceptionSynchronized

Java Problem Overview


Are there any unclear side effects to throwing an exception from within a synchronized clause? What happens to the lock?

private void doSomething() throws Exception {...}

synchronized (lock) {   
    doSomething();       
}

Java Solutions


Solution 1 - Java

I see no side-effect.

The lock is guaranteed to be terminated in all cases, and an exception is no exception (pun intended).

Solution 2 - Java

As you would hope, the lock is released normally.

For reference, the appropriate section of the JLS which guarantees this behaviour is § 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.

('abrupt completion' is defined elsewhere in the JLS to include exceptions from JVM, exceptions raised by throw, and use of the break, continue, or return statements to transfer outside the block.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYossaleView Question on Stackoverflow
Solution 1 - JavaKLEView Answer on Stackoverflow
Solution 2 - JavaCowanView Answer on Stackoverflow