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












0















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









share|improve this question


















  • 5





    The original thread calls theLock.wait() which means it releases the lock and waits to be notified. Then the second thread obtains the lock, calls notify, and releases the lock. Then the first thread wakes up, obtains the lock, and continues.

    – Slaw
    Nov 14 '18 at 13:27


















0















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









share|improve this question


















  • 5





    The original thread calls theLock.wait() which means it releases the lock and waits to be notified. Then the second thread obtains the lock, calls notify, and releases the lock. Then the first thread wakes up, obtains the lock, and continues.

    – Slaw
    Nov 14 '18 at 13:27
















0












0








0








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









share|improve this question














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






java multithreading synchronized synchronized-block






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 13:24









VitaliiVitalii

2,11962555




2,11962555








  • 5





    The original thread calls theLock.wait() which means it releases the lock and waits to be notified. Then the second thread obtains the lock, calls notify, and releases the lock. Then the first thread wakes up, obtains the lock, and continues.

    – Slaw
    Nov 14 '18 at 13:27
















  • 5





    The original thread calls theLock.wait() which means it releases the lock and waits to be notified. Then the second thread obtains the lock, calls notify, and releases the lock. Then the first thread wakes up, obtains the lock, and continues.

    – Slaw
    Nov 14 '18 at 13:27










5




5





The original thread calls theLock.wait() which means it releases the lock and waits to be notified. Then the second thread obtains the lock, calls notify, and releases the lock. Then the first thread wakes up, obtains the lock, and continues.

– Slaw
Nov 14 '18 at 13:27







The original thread calls theLock.wait() which means it releases the lock and waits to be notified. Then the second thread obtains the lock, calls notify, and releases the lock. Then the first thread wakes up, obtains the lock, and continues.

– Slaw
Nov 14 '18 at 13:27














1 Answer
1






active

oldest

votes


















5














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.







share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301296%2fwhy-synchronized-lock-was-entered-twice-by-different-threads%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    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.







    share|improve this answer




























      5














      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.







      share|improve this answer


























        5












        5








        5







        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.







        share|improve this 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.








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 13:28









        Andrew HenleAndrew Henle

        19.7k21333




        19.7k21333
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301296%2fwhy-synchronized-lock-was-entered-twice-by-different-threads%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python