java synchronization and exception handling

和自甴很熟 提交于 2019-12-07 17:33:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!