2
votes

sleep() maintains the lock but wait() does not,

my thinking on wait is that it releases the lock as to give other threads a chance to acquire the monitor on that thread while he is waiting.

but having doubt with sleep() why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping

3
"why thread maintains the lock while sleeping" What lock? Thread.sleep() is a static method. There is no lock associated with a Thread.sleep() call because there is no object associated with it.Solomon Slow

3 Answers

2
votes

why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping

Consider the below scenario:-

private Object objLock = new Object();

public void myMethod() {
   .... 
   synchronized(objLock) {

      Thread.sleep(1000);   // make the current running thread sleep for 1 second only. 
      ... // Code here which needs to be executed immediately after 1 second sleep time
   }
   ....
}

If at all JVM relesed lock when sleep was called in the above code then when it comes back to runnable state (resumption of execution will depend on scheduling and the availability of processors on which to execute the thread as per JLS Sleep ) your program may not resume at all if another thread by chance took a lock which would make the program behaviour inconsistent. This could be one of the reasons why it doesnot release any locks.

2
votes

Thread.sleep doesn't have anything to do with locking.

Object.wait needs to be called when holding a lock because the test for the condition to stop waiting needs to be done while holding the lock, in order to have a consistent view of the condition. But usually a thread isn't holding a lock while sleeping.

Sleeping while holding a lock would seem like really bad behavior. But if you need multiple locks, where you acquire one, and have to back off before retrying getting the other, then sleeping while holding a lock might make sense. If calling sleep released locks, this kind of back-off tactic would not work.

Having Thread.sleep be oblivious to locks makes the API simpler and gives the programmer more options (by not totally ruling out its use by a thread that needs to hold onto a lock).

0
votes

Q: What does Thread.sleep(n) do?
A: NOTHING. Absolutely nothing at all.

Q: How long does it take?
A: At least n milliseconds if the thread is not interrupted.

You don't need to know much else about Thread.sleep().