java 在同步子句中抛出异常的副作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2019339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Side effects of throwing an exception inside a synchronized clause?
提问by Yossale
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();
}
回答by KLE
I see no side-effect.
我看没有副作用。
The lock is guaranteed to be terminatedin all cases, and an exception is no exception (pun intended).
该锁是保证被终止在所有情况下,和一个异常也不例外(双关语意)。
回答by Cowan
As you would hope, the lock is released normally.
如您所愿,锁会正常释放。
For reference, the appropriate section of the JLS which guarantees this behaviour is § 14.19:
作为参考,保证这种行为的 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.
如果 Block 的执行正常完成,则锁被解锁并且同步语句正常完成。如果 Block 的执行因任何原因突然完成,则锁被解锁,然后同步语句出于同样的原因突然完成。
('abrupt completion' is defined elsewhere in the JLS to include exceptions from JVM, exceptions raised by throw, and use of the break, continue, or returnstatements to transfer outside the block.)
(“急剧完成”在别处JLS定义为包括从JVM异常,通过引发的异常throw,和使用break,continue或return语句到块外转移。)

