Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if thread throws a Exception inside synchronised block

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.

like image 821
Midhun Pottammal Avatar asked Jun 05 '15 06:06

Midhun Pottammal


People also ask

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

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.

What happens if a thread throws an exception?

If there is an exception handler installed for the ThreadGroup, the JVM passes the exception to it. If it's an AWT thread, you can install an event handler for otherwise unhandled exceptions. Otherwise the JVM handles it.

Can a thread enter a synchronized block without acquiring a lock?

Java synchronized keyword is re-entrant in nature it means if a synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.

Does synchronized block thread?

A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.


1 Answers

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.

like image 146
Patricia Shanahan Avatar answered Oct 04 '22 02:10

Patricia Shanahan