Reputation: 4010
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 ?
Upvotes: 2
Views: 4491
Reputation: 41220
yes it is. It'll wait up to return from function which happen after executing finally block execution.
Upvotes: 0
Reputation: 33544
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.
Upvotes: 1
Reputation: 726809
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");
}
}
Upvotes: 2