18

I have read that Thread.sleep() will pause the currently running thread for the time specified after which it goes back to runnable state waiting for it's turn to run.

Also, if called from synchronized context, sleep() doesn't release the lock it holds. So I was wondering when it will release the lock. If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.

I am not sure if I am asking valid question. But please help me out.

2 Answers 2

24

So I was wondering when it will release the lock.

It will release the lock upon exit from the synchronized block, and not earlier.

If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.

Quite simply, other threads will not be able to enter code that's synchronized on the same object that the sleeping thread.

To summarize, calling Thread.sleep() from a synchronized block is likely not a good idea.

7
  • 5
    Really, calling Thread.sleep() is likely not a good idea at all. If there's something you can do now, you should do it now. If you have to wait for something before there's anything you can do, you should wait for that something rather than sleeping. May 19, 2012 at 9:24
  • 2
    @DavidSchwartz: I agree. While there are legitimate uses for Thread.sleep(), it is often used where it shouldn't be.
    – NPE
    May 19, 2012 at 9:30
  • 2
    Well explained, but saying "To summarize, calling Thread.sleep() from a synchronized block is likely not a good idea." is going too far. Sometimes you want to wait and keep the lock.
    – Jesus
    Oct 9, 2015 at 12:51
  • 1
    @UtenteStack If you're waiting for the phone to ring, you should wait for the phone to ring. You shouldn't go to sleep for 4 seconds and then check if the phone rang while you were asleep. If there's something you're waiting for, you should wait for that something rather than sleeping. Feb 8, 2016 at 17:45
  • 1
    The code that permits the calls to the API should use a timer to trigger a call to notify. The code that makes the API calls should be waiting for permission using wait. Even if you combine these two functions into one piece of code, the operation will be triggered by the timer, so there's no need to call sleep. Rather than have a thread wait for something to happen so that it can do work, have the thing happening cause the work to be done so nothing needs to wait. Feb 8, 2016 at 21:31
20

If you use Object.wait instead of Thread.sleep, the lock from the synchronized block will be released.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.