If an exception is thrown inside a synchronized block will the lock on the object that was synchronized be automatically released?

Alex Chaffee

It depends on whether the exception escapes (passes through) the synchronized block or not. Consider the following example.


try {
 synchronized (o) {
   try {
    doSomething();
   }
   catch (A) {
    a();
   }
 }
}
catch (B) {
 b();
}

If doSomething() throws an exception of type A, it will be caught by the inner try block, and the lock on o will still be active during method a(). However, if doSomething() throws an exception of type B, it will be caught by the inner try block -- on its way out of the series of nested stack frames -- and the lock will be released before method b() is invoked.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact