问题
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( "" );
}
回答1:
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."
回答2:
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.
回答3:
There should be no problem. The lock is released whatever the execution path is (return, exception...) See this for details.
来源:https://stackoverflow.com/questions/8375172/java-synchronization-and-exception-handling