by BehindJava

Is it possible to use Object.wait(millisec) to simulate sleep in Java Threads

Home » java » Is it possible to use Object.wait(millisec) to simulate sleep in Java Threads

This is a quick tutorial on stating the differences between wait and sleep method in Java Threads.

Note that there is one key difference in using Object.wait() and Thread.sleep() inside a synchronization block: Thread.sleep() does not release the locked monitor, so no-one else can become the owner of the monitor.

In addition, Object.wait() does not guarantee that the delay indicated will be obeyed strictly. First of all, after the delay passes, the thread may still be waiting for another thread that has become the monitor owner in the meantime; and it may compete with other threads waiting to grab the monitor.

Second, the mythical spurious wake-up, as it is described in the Java 6 API javadoc:

  • A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup.

Unlikely as it is, every piece of code using Object.wait() should take it into consideration.

Example:

Object lock = new Object();

synchronized( lock ) 
{
   try
   {
       lock.wait( 50000 );
       Thread.sleep( 3000 );
   } 
   catch(Exception ex)
   {
   }
}

Thread polling a resource every minute, but you want to be woken if something’s happened (e.g. the resource location has changed, or the timer frequency has changed, or the program wants to quit in a graceful manner).

Using wait/notify works extremely well for that - it’s definitely cleaner than calling interrupt on the thread from elsewhere, as it doesn’t matter if the notify occurs while you’re actually processing instead of waiting.