What happens if a thread throws an exception inside a synchronized block

Consider several threads trying to access a critical section of what happens in one thread that occurs. An exception is inside a synchronized block that has wait () and notify () to get and release the lock.

+5
source share
3 answers

The synchronization monitor will be released: "If the body is completed, as usual, or suddenly, the unlock action is automatically performed on the same monitor." The Java Language Specification 17.1. Sync

Other threads will be able to continue synchronization and call wait and notify.

If an exception thread contains some critical program logic resource, you may need to use try-finally to ensure that it is freed.

+7
source

As mentioned, if an exception occurs, it should be handled / thrown to continue execution, otherwise execution will stop. Thus, in your scenario the same way, if an exception occurs, then it will be processed, and then the lock will be released.

0
source

You probably think of locks the same way resources do (Connections, I / O), but unlike resource locks, they will be released as soon as the executable stream reaches the exit boundary of the critical section (closing bracket of the monitor / synchronized block), regardless whether an exception is selected.

Contact: synchronized statement

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

0
source

All Articles