What will happen if thread throws a Exception inside synchronised block

。_饼干妹妹 提交于 2020-12-28 18:29:40

问题


Consider multiple threads are trying to access critical section, what will happen one thread that occurs Exception inside a synchronized block it having wait() and notify() to accrue and release lock.


回答1:


The synchronization monitor will be released: "If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor." Java Language Specification 17.1. Synchronization.

Other threads will be able to continue synchronizing, and calling wait and notify.

If the thread with the exception is holding some critical program logic resource, you may need to use try-finally to ensure it is released.




回答2:


Probably you are thinking of locks in the same way as resources(Connections, I/O) but unlike resources lock will be released as soon as the executing Thread reaches the exit boundary of critical section(monitor/ synchronized block closing parenthesis) regardless of Exception being thrown.

Refer: synchronized statement

If execution of the Block completes abruptly for any reason, then the monitor is unlocked and the synchronized statement completes abruptly for the same reason.




回答3:


As mentioned if an exception occurs then it should be handled/thrown to continue the execution or else execution will stop. So, it is same in your scenario if an exception happens then it would be handled and further the lock will be released.



来源:https://stackoverflow.com/questions/30660236/what-will-happen-if-thread-throws-a-exception-inside-synchronised-block

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