Search code examples
javamultithreadinglockingreentrancy

Reentrancy in synchronized methods


Are synchronized methods reentrant?

I have this code:

public class Main {
    
    synchronized void m1() {
        //some code
        m2();
        //some code
    }
    
    synchronized void m2(){
        //some code
    }    
    
}

Say two threads (Thread A and Thread B) try to access m1() at the same time. Thread A takes lock first. After some time Thread A calls m2(), which is also synchronized on same object.

As I don't want to make any guesses can someone tell me this: Is there any guarantee what will happen when Thread A calls m2()? I mean once Thread A calls m2(), does it 'leave lock' at all? Because technically it left method's frame, so will it leave lock as well?

[EDIT]: Does Thread A get to run m2() every time once it calls it? Or does it leave lock so both Thread A and Thread B would race for their goals?


Solution

  • In Java locks are reentrant. If Thread A holds the lock, then it can start executing method m1. Eventually it will invoke method m2, since Thread A already holds the lock, it does not have to reacquire the lock again to execute method m2. Internally the lock keeps the owner field to track this. Even if the lock is already held, since the caller of m2 is the owner of the lock, the access is granted. This design strategy prevents deadlocks.