同步关键字异常安全吗?
可能的重复:
在同步子句中引发异常的副作用?< /a>
我想知道 synchronized
是否是异常安全的?比如说,同步块内发生未捕获的异常,锁会被释放吗?
Possible Duplicate:
Side effects of throwing an exception inside a synchronized clause?
I am wondering if synchronized
is exception-safe? Say, an uncaught exception happens within the synchronized block, will the lock be released?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如有疑问,请查看 Java 语言规范。在 17.1 部分中,您会发现:
When in doubt, check the Java Language Specification. In section 17.1 you'll find:
只有 System.exit 才能阻止块正常退出。这意味着
finally
块不会被调用,锁也不会被释放。打印
并悬挂。 :|
Only a System.exit prevents a block exiting normally. It means
finally
blocks are not called and locks are not released.prints
and hangs. :|
是的,会的。 Synchronize 关键字的主要目的是使多线程编码更容易。
Yes, it will. The major point of the synchronize keyword is to make multi-threaded coding easier.
是的,如果抛出异常但未被捕获,对象将被解锁。
您可以在此处找到一些代码示例。
Yes the object will become unlocked if an exception is thrown and not caught.
You can find some code examples here.
是的,会的。
附带说明一下,
try-finally
构造将确保 try 退出时执行 finally 块Yes it will.
As a side note, the
try-finally
construct will ensure the finally block will be executed when the try exits