Search code examples
javasynchronizedtry-finally

Behavior of a synchronized method with try and finally


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");
        }
    }