Behavior of a synchronized method with try and finally
-
10-06-2021 - |
Question
Assume the following method:
public synchronized void a(){
try{
System.out.println("a");
return;
}finally{
System.out.println("a, finally");
}
}
I understand that the finally block will still be executed even after the return statement. One can even "override" the return value ! But my question is, will the method be unlocked after the return statement or after finally ?
Solution
Since return
is not executed before finally
block has finished, and because the entire method is synchronized
, the lock is not released until after the finally
block has finished.
If you need to release the lock on exception rather than on returning from the method, you can nest your synchronized
block inside the try
/finally
block:
public void a(){
try {
synchronized (this) {
System.out.println("a");
return;
}
} finally{
System.out.println("a, finally");
}
}
OTHER TIPS
1st of all finally will execute before the return statement....
Secondly the lock will be released only when the thread has finished executing the complete method.. ie(till the end braces of this method), Moreover this lock is of the object, so not only this method, but all the synchronized method in that class are locked.
yes it is. It'll wait up to return from function which happen after executing finally block execution.