Reputation: 4223
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( "" );
}
Upvotes: 4
Views: 4114
Reputation: 21449
There should be no problem. The lock is released whatever the execution path is (return, exception...) See this for details.
Upvotes: 1
Reputation: 22993
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."
Upvotes: 7
Reputation: 122001
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.
Upvotes: 3