What will happen when an exception arises from within a synchronized code block? Will lock be retained or released?

By | August 14, 2019

In this blog post we will discuss about one of the very important java interview question  What will happen when an exception arises from within a synchronized code block? Will lock be retained or released? 

  • When an exception occurs from within a synchronized code block, then JVM smartly releases all the locks acquired by the current thread and will start unwinding the execution stack, till the exception is handled using catch block, otherwise killing the thread.
  • JVM does take care to release lock when we write explicit locking code using Lock interface. In that case we need to release the lock manually in the finally block.

You may also like:

What are common multi-threading issues faced by Java Developers?
What are different states of a Thread? What does those states tell us?
What happens when wait() & notify() methods are called?
What is difference between sleep(), yield() and wait() method?
What is difference between Callable and Runnable Interface?

That’s all about  What will happen when an exception arises from within a synchronized code block? Will lock be retained or released?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *