Wait and sleep
2 posts in topic
Flat View  Flat View

Posted By:   sreedhar_reddy
Posted On:   Monday, January 28, 2002 11:12 PM

What is the difference between sleep and wait methods?

Re: Wait and sleep

Posted By:   Dane_Foster  
Posted On:   Saturday, February 2, 2002 11:03 AM

In addition to what Duncan said there is one more important difference between sleep and wait. When a Thread goes to sleep it retains any monitors that it had prior to going to sleep. When a Thread calls wait it releases the monitor of the object that itÂ’s waiting on. It is extremely important that you are aware of this because sleep is one of the easiest ways to create a deadlock condition in your code. The deadlock occurs because the Thread went to sleep while holding on to the monitor so other Threads that are contending for the monitor can't get it. If the Thread is asleep for a short time and releases the monitor relatively quickly after waking up you might not even notice that you have a deadlock condition in your code thus the bug can go undetected for a long time. But the problem can begin to compound itself under the following conditions:
1 - There are a lot of Threads contending for the monitor while the Thread is sleeping. So even though the Thread may be sleeping for a short period your code can suffer a serious degradation in performance because of the contention overhead.

2 - The Thread sleeps for an extend period of time.

3 - The sleep is happening in a loop that won't exit until some condition has been met but the condition changing is dependent on some other Thread gaining the monitor that the sleeping Thread is holding on to. This is the classic deadlock scenario.

Finally, here is a good Thread programming practice that you should always follow. If there is a call to wait on an object without a timeout being specified, you MUST ensure that eventually there is a call to notify or notifyAll on the same object. Failing to do what I've just said is another major case of deadlock in Java code.

Happy coding.

Re: Wait and sleep

Posted By:   Duncan_Forster  
Posted On:   Tuesday, January 29, 2002 12:37 AM

sleep as you would guess sleeps a thread for certain amount of time. Also sleep is only called on a thread instance.

wait can be called on any object instance. wait will cause the current thread to be added to the wait set for the object instance you called it on. Threads that belong to this wait set will sleep until they are awoken by another thread executing notify/notifyAll or if a timeout was supplied, after the timeout period.

Note: Calling notify/notifyAll does not guarantee the thread you want to wake up will be awoken and enabled for thread scheduling, if there is more than one thread in the wait set it could be another thread that is awoken.

About | Sitemap | Contact