Two threads executing synchronized block simultaneously

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
8
down vote

favorite












Below is the code where a Thread enters a synchronized block, waits for 5seconds and then exits. I have started two Thread instances simultaneously.



The expectation was one of the threads will own the lock on the synchronized object & the other will wait. After 5 seconds, when the lock owner exits, the waiting thread will execute.



But, in actual, both the threads are executing the synchronized block simultaneously and also exiting at the same time.




Expected Output:




Thread-X <timeX> received the lock.
Thread-X <timeX+5s> exiting...
Thread-Y <timeY> received the lock.
Thread-Y <timeY+5s> exiting...



Actual Output:




Thread-X <time> received the lock.
Thread-Y <time> received the lock.
Thread-X <time+5s> exiting...
Thread-Y <time+5s> exiting...


Any explanation of the above behavior will be really helpful. Am I missing something here?



import java.text.SimpleDateFormat;
import java.util.Date;

public class Test2
public static void main(String args)
MyRunnable m = new MyRunnable();
Thread t = new Thread(m);
Thread t1 = new Thread(m);
t.start();
t1.start();



class MyRunnable implements Runnable
@Override
public void run()
synchronized (this)
try
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " received the lock.");
wait(5000);
date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " exiting...");
catch(InterruptedException ie)












share|improve this question























  • Synchronized block in the example is effectively he synchronized run() method. It's been already answered here stackoverflow.com/questions/19688666/synchronized-run-method
    – dawid gdanski
    2 hours ago






  • 1




    @dawidgdanski That's just plain wrong. The question uses a single object for providing the lock.
    – Markus
    1 hour ago










  • With all my knowledge on the about the synchronization I was not aware of releasing the monitor lock on wait() invocation. Thanks for correcting me.
    – dawid gdanski
    7 mins ago














up vote
8
down vote

favorite












Below is the code where a Thread enters a synchronized block, waits for 5seconds and then exits. I have started two Thread instances simultaneously.



The expectation was one of the threads will own the lock on the synchronized object & the other will wait. After 5 seconds, when the lock owner exits, the waiting thread will execute.



But, in actual, both the threads are executing the synchronized block simultaneously and also exiting at the same time.




Expected Output:




Thread-X <timeX> received the lock.
Thread-X <timeX+5s> exiting...
Thread-Y <timeY> received the lock.
Thread-Y <timeY+5s> exiting...



Actual Output:




Thread-X <time> received the lock.
Thread-Y <time> received the lock.
Thread-X <time+5s> exiting...
Thread-Y <time+5s> exiting...


Any explanation of the above behavior will be really helpful. Am I missing something here?



import java.text.SimpleDateFormat;
import java.util.Date;

public class Test2
public static void main(String args)
MyRunnable m = new MyRunnable();
Thread t = new Thread(m);
Thread t1 = new Thread(m);
t.start();
t1.start();



class MyRunnable implements Runnable
@Override
public void run()
synchronized (this)
try
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " received the lock.");
wait(5000);
date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " exiting...");
catch(InterruptedException ie)












share|improve this question























  • Synchronized block in the example is effectively he synchronized run() method. It's been already answered here stackoverflow.com/questions/19688666/synchronized-run-method
    – dawid gdanski
    2 hours ago






  • 1




    @dawidgdanski That's just plain wrong. The question uses a single object for providing the lock.
    – Markus
    1 hour ago










  • With all my knowledge on the about the synchronization I was not aware of releasing the monitor lock on wait() invocation. Thanks for correcting me.
    – dawid gdanski
    7 mins ago












up vote
8
down vote

favorite









up vote
8
down vote

favorite











Below is the code where a Thread enters a synchronized block, waits for 5seconds and then exits. I have started two Thread instances simultaneously.



The expectation was one of the threads will own the lock on the synchronized object & the other will wait. After 5 seconds, when the lock owner exits, the waiting thread will execute.



But, in actual, both the threads are executing the synchronized block simultaneously and also exiting at the same time.




Expected Output:




Thread-X <timeX> received the lock.
Thread-X <timeX+5s> exiting...
Thread-Y <timeY> received the lock.
Thread-Y <timeY+5s> exiting...



Actual Output:




Thread-X <time> received the lock.
Thread-Y <time> received the lock.
Thread-X <time+5s> exiting...
Thread-Y <time+5s> exiting...


Any explanation of the above behavior will be really helpful. Am I missing something here?



import java.text.SimpleDateFormat;
import java.util.Date;

public class Test2
public static void main(String args)
MyRunnable m = new MyRunnable();
Thread t = new Thread(m);
Thread t1 = new Thread(m);
t.start();
t1.start();



class MyRunnable implements Runnable
@Override
public void run()
synchronized (this)
try
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " received the lock.");
wait(5000);
date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " exiting...");
catch(InterruptedException ie)












share|improve this question















Below is the code where a Thread enters a synchronized block, waits for 5seconds and then exits. I have started two Thread instances simultaneously.



The expectation was one of the threads will own the lock on the synchronized object & the other will wait. After 5 seconds, when the lock owner exits, the waiting thread will execute.



But, in actual, both the threads are executing the synchronized block simultaneously and also exiting at the same time.




Expected Output:




Thread-X <timeX> received the lock.
Thread-X <timeX+5s> exiting...
Thread-Y <timeY> received the lock.
Thread-Y <timeY+5s> exiting...



Actual Output:




Thread-X <time> received the lock.
Thread-Y <time> received the lock.
Thread-X <time+5s> exiting...
Thread-Y <time+5s> exiting...


Any explanation of the above behavior will be really helpful. Am I missing something here?



import java.text.SimpleDateFormat;
import java.util.Date;

public class Test2
public static void main(String args)
MyRunnable m = new MyRunnable();
Thread t = new Thread(m);
Thread t1 = new Thread(m);
t.start();
t1.start();



class MyRunnable implements Runnable
@Override
public void run()
synchronized (this)
try
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " received the lock.");
wait(5000);
date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " exiting...");
catch(InterruptedException ie)









java multithreading synchronized thread-synchronization






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 1 hour ago









Maxim Egorushkin

80.5k1195174




80.5k1195174










asked 2 hours ago









somnathchakrabarti

1,03764268




1,03764268











  • Synchronized block in the example is effectively he synchronized run() method. It's been already answered here stackoverflow.com/questions/19688666/synchronized-run-method
    – dawid gdanski
    2 hours ago






  • 1




    @dawidgdanski That's just plain wrong. The question uses a single object for providing the lock.
    – Markus
    1 hour ago










  • With all my knowledge on the about the synchronization I was not aware of releasing the monitor lock on wait() invocation. Thanks for correcting me.
    – dawid gdanski
    7 mins ago
















  • Synchronized block in the example is effectively he synchronized run() method. It's been already answered here stackoverflow.com/questions/19688666/synchronized-run-method
    – dawid gdanski
    2 hours ago






  • 1




    @dawidgdanski That's just plain wrong. The question uses a single object for providing the lock.
    – Markus
    1 hour ago










  • With all my knowledge on the about the synchronization I was not aware of releasing the monitor lock on wait() invocation. Thanks for correcting me.
    – dawid gdanski
    7 mins ago















Synchronized block in the example is effectively he synchronized run() method. It's been already answered here stackoverflow.com/questions/19688666/synchronized-run-method
– dawid gdanski
2 hours ago




Synchronized block in the example is effectively he synchronized run() method. It's been already answered here stackoverflow.com/questions/19688666/synchronized-run-method
– dawid gdanski
2 hours ago




1




1




@dawidgdanski That's just plain wrong. The question uses a single object for providing the lock.
– Markus
1 hour ago




@dawidgdanski That's just plain wrong. The question uses a single object for providing the lock.
– Markus
1 hour ago












With all my knowledge on the about the synchronization I was not aware of releasing the monitor lock on wait() invocation. Thanks for correcting me.
– dawid gdanski
7 mins ago




With all my knowledge on the about the synchronization I was not aware of releasing the monitor lock on wait() invocation. Thanks for correcting me.
– dawid gdanski
7 mins ago












3 Answers
3






active

oldest

votes

















up vote
11
down vote













The answer lies here: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait(long)



Quote:




[...] This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. [...]







share|improve this answer





























    up vote
    2
    down vote













    Use



    Thread.sleep(5000);


    JavaDocs for Thread.sleep:




    Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.







    share|improve this answer





























      up vote
      1
      down vote













      Guarded Blocks:




      When wait is invoked, the thread releases the lock and suspends
      execution.




      Only one thread can execute a synchronized block guarded by the same object! Calling wait(...) in your example releases the lock, thus allowing another thread to acquire the lock.






      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',
        convertImagesToLinks: true,
        noModals: false,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        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%2f52477347%2ftwo-threads-executing-synchronized-block-simultaneously%23new-answer', 'question_page');

        );

        Post as a guest






























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        11
        down vote













        The answer lies here: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait(long)



        Quote:




        [...] This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. [...]







        share|improve this answer


























          up vote
          11
          down vote













          The answer lies here: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait(long)



          Quote:




          [...] This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. [...]







          share|improve this answer
























            up vote
            11
            down vote










            up vote
            11
            down vote









            The answer lies here: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait(long)



            Quote:




            [...] This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. [...]







            share|improve this answer














            The answer lies here: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait(long)



            Quote:




            [...] This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. [...]








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 53 mins ago









            Hulk

            2,14411432




            2,14411432










            answered 1 hour ago









            Markus

            2,07121121




            2,07121121






















                up vote
                2
                down vote













                Use



                Thread.sleep(5000);


                JavaDocs for Thread.sleep:




                Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.







                share|improve this answer


























                  up vote
                  2
                  down vote













                  Use



                  Thread.sleep(5000);


                  JavaDocs for Thread.sleep:




                  Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.







                  share|improve this answer
























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    Use



                    Thread.sleep(5000);


                    JavaDocs for Thread.sleep:




                    Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.







                    share|improve this answer














                    Use



                    Thread.sleep(5000);


                    JavaDocs for Thread.sleep:




                    Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.








                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 49 mins ago









                    Hulk

                    2,14411432




                    2,14411432










                    answered 1 hour ago









                    Selindek

                    38419




                    38419




















                        up vote
                        1
                        down vote













                        Guarded Blocks:




                        When wait is invoked, the thread releases the lock and suspends
                        execution.




                        Only one thread can execute a synchronized block guarded by the same object! Calling wait(...) in your example releases the lock, thus allowing another thread to acquire the lock.






                        share|improve this answer


























                          up vote
                          1
                          down vote













                          Guarded Blocks:




                          When wait is invoked, the thread releases the lock and suspends
                          execution.




                          Only one thread can execute a synchronized block guarded by the same object! Calling wait(...) in your example releases the lock, thus allowing another thread to acquire the lock.






                          share|improve this answer
























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            Guarded Blocks:




                            When wait is invoked, the thread releases the lock and suspends
                            execution.




                            Only one thread can execute a synchronized block guarded by the same object! Calling wait(...) in your example releases the lock, thus allowing another thread to acquire the lock.






                            share|improve this answer














                            Guarded Blocks:




                            When wait is invoked, the thread releases the lock and suspends
                            execution.




                            Only one thread can execute a synchronized block guarded by the same object! Calling wait(...) in your example releases the lock, thus allowing another thread to acquire the lock.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 47 mins ago

























                            answered 1 hour ago









                            Oleksandr

                            6,91833365




                            6,91833365



























                                 

                                draft saved


                                draft discarded















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52477347%2ftwo-threads-executing-synchronized-block-simultaneously%23new-answer', 'question_page');

                                );

                                Post as a guest













































































                                Comments

                                Popular posts from this blog

                                What does second last employer means? [closed]

                                List of Gilmore Girls characters

                                One-line joke