What will happen if thread throws a Exception inside synchronised block

后端 未结 3 1978
北恋
北恋 2021-02-05 18:18

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

相关标签:
3条回答
  • 2021-02-05 19:06

    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.

    0 讨论(0)
  • 2021-02-05 19:12

    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.

    0 讨论(0)
  • 2021-02-05 19:12

    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.

    0 讨论(0)
提交回复
热议问题