Question

I have a problem to understand how works the nested synchronized. i give here 2 examples to make make a comparison:

//example 1
public class Account {
    int balance = 1000;
    Object lock = new Object();

    public int getBalance() throws InterruptedException {
        synchronized(lock) {
            // step 1- Thread 1 enter here and sleep
            Thread.sleep(20);
            return balance;
        }
    }
    public void setBalance(int amount) {
        // step 2 - Thread 2 have to wait until thread 1 release the lock.
        synchronized(lock) {
            this.balance = amount;
        }
    }
}

the example above is clear and logic.
now look the example 2:

public class Account {
    int balance = 1000;
    Object lock = new Object();

    public int getBalance() {
        synchronized(lock) {
            // step 1 - Thread 1 enter here and lock the object.
            synchronized(lock) { //same lock 
                //step 2 - Thread 1 can enter here also if the lock is already locked why????

                //...do something...
                return balance;
            }
        }
    }
}


I don't understand in the example 2, why the same thread can enter on the same lock 2 times if the outer lock is already locked...

Was it helpful?

Solution

The inner lock serves no function, in this case. Java uses recursive mutexes, so a thread that holds a lock on a given mutex can lock it again, and a lock count is kept. Only when the last synchronized block is exited, is the mutex actually unlocked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top