15

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.

Midhun Pottammal
  • 1,107
  • 1
  • 11
  • 25
  • This is answered here , http://stackoverflow.com/questions/12521776/what-happens-to-the-lock-when-thread-crashes-inside-a-synchronized-block and http://stackoverflow.com/questions/2019339/side-effects-of-throwing-an-exception-inside-a-synchronized-clause – Kenneth Clark Jun 05 '15 at 07:05
  • @KennethClark what will happen that lock was not manually released. if makes any dead locks – Midhun Pottammal Jun 05 '15 at 07:06
  • The lock is guaranteed to be terminated in all cases – Kenneth Clark Jun 05 '15 at 07:11
  • Possible duplicate of [Side effects of throwing an exception inside a synchronized clause?](http://stackoverflow.com/questions/2019339/side-effects-of-throwing-an-exception-inside-a-synchronized-clause) – Alex K Jan 18 '17 at 11:53

3 Answers3

17

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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
1

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.

Nitin Dandriyal
  • 1,559
  • 11
  • 20
0

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.

Viswanath Donthi
  • 1,791
  • 1
  • 11
  • 12
  • what will happen that lock was not manually released. if makes any dead locks – Midhun Pottammal Jun 05 '15 at 07:06
  • Generally, we should take care of all scenarios to avoid possibility of dead locks. If any dead lock is invoked then we can't do anything from our end except restarting the application. To avoid deadlocks I suggest you to read about "Inter-Thread Communication in Java". – Viswanath Donthi Jun 05 '15 at 07:10