Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.396 :

Posted: Tue Apr 10, 2018 2:39 am
by TwistedLizard
If a synchronized method throws an exception in its execution, any locks acquired by the method are released automatically.
Am I correct in supposing that this only applies to a situation where the exception is thrown out of the method?

If an exception is thrown during a method's execution, but it's caught within that method, would any acquired locks would still be held?

For example

Code: Select all

class SynchronizedMethodTest{
  synchronized void m(){
    try{
      //do dangerous stuff
      throw new Exception();
    }catch(Exception e){}
    //method still has lock on class instance at this point? [A]
  }
  public static void main(String[] args){
    new SynchronizedMethodTest().m();
  }
}
at [A], is it correct that the method's lock on the class instance is still held?

Re: About Question com.enthuware.ets.scjp.v6.2.396 :

Posted: Tue Apr 10, 2018 5:46 am
by admin
Yes, that is correct. The exception has to get out of the method.

Re: About Question com.enthuware.ets.scjp.v6.2.396 :

Posted: Tue Apr 10, 2018 1:51 pm
by TwistedLizard
Thanks. That makes sense.

Re: About Question com.enthuware.ets.scjp.v6.2.396 :

Posted: Tue Feb 04, 2025 11:16 am
by raphaelzintec
It's not mandatory to put lock/unlock in try catch but recommended and question is not mentioning that it's inside try/catch