Why `synchronized (lock)` was entered twice by different threads?

116 Views Asked by At

In this simple example I have two synchronized (theLock) that are accessed by different threads

public class Main {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("start");

        final Object theLock = new Object();

        synchronized (theLock) {
            System.out.println("main thread id : " + Thread.currentThread().getId());

            new Thread(() -> {
                System.out.println("new thread id : " + Thread.currentThread().getId() + ". Inside thread");

                // before entering this section new thread should be blocked as `theLock` is already acquired
                synchronized (theLock) {
                    System.out.println("inside synchronized");
                    theLock.notify();
                }
            }).start();

            theLock.wait();
        }

        System.out.println("end");
    }
}

Why the newly created thread can access to synchronized (theLock) section inside? As far as I understand, theLock is already acquired by the main thread and the new one should block forever. Instead I see that it enters to synchronized as well.

Here is an output

start
main thread id : 1 
new thread id : 13. Inside thread
inside synchronized
end
1

There are 1 best solutions below

0
On BEST ANSWER

The call to wait() releases the lock. Per wait() Javadoc (bolding mine):

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.