June 19, 2022

Difference Between sleep() And wait() Methods in Java

In this post we’ll see the difference between sleep() and wait() methods in Java. Since both of these methods sleep() and wait() cause the currently executing thread to suspend its execution some users find it confusing to differentiate between sleep and wait methods. So let’s try to see the difference between sleep() and wait() methods in Java.

sleep() Vs wait() in Java

The main differences between these two methods arises from the fact that the wait method is used for inter-thread communication and works in tandem with notify() and notifyAll() methods and it can only be used with in the synchronized context.
Where as sleep() method can be used in any context.

  1. sleep() method is a static method defined in Thread class and calling the Thread.sleep() method causes the currently executing thread to suspend execution for the specified time.
    wait() method is defined in the Object class and it is an instance method (called on the object of the class).
  2. sleep() method works on the current thread.
    Since wait() method is defined in Object class and called on an object, it is used for inter-thread communication. When the notify() or notifyAll() method is called on the same object it causes the thread(s) currently waiting on the same object to wake up.
  3. sleep() method can be called from any context. There is no compulsion that it has to be called with in a synchronized method or block.
    wait() method, when called, results in the current thread to release the object’s lock it holds. Since a thread acquires an object’s lock when entering a synchronized method or block, wait() method can only be called with in a synchronized context. If you call wait() method from a method (or block) that is not synchronized, IllegalMonitorStateException will be thrown at run time.

    Refer Why wait(), notify() and notifyAll() Methods Must be Called From a Synchronized Method or Block to know the reason why wait, notify and notifyAll methods have to called from a synchronized context.

  4. Current thread doesn’t have to release the lock it holds if sleep() method is called with in a synchronized context.
    Current thread has to release the lock and go to waiting state when wait() method is called, that gives another thread a chance to acquire lock and enter a synchronized method or block.
  5. A thread that has been paused by calling the sleep() method awakes after the specified time (as given in sleep method) has elapsed or the thread is interrupted.
    A thread that is in waiting state because wait() method is called comes out of waiting state when notify or notifyAll() method is called on the same object. There are two variants of wait() method wait(long timeout) and wait(long timeout, int nanos) where time of waiting can be specified. In case any of these wait() methods are used the thread is awakened if it is notified or given amount of real time has elapsed. Waiting thread can also be interrupted.

Java Sleep method example

public class InterruptDemo implements Runnable {
  @Override
  public void run() {
    synchronized(this){
      for(int i = 0; i < 5; i++){
        System.out.println(Thread.currentThread().getName() + " Value - " + i);
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          System.out.println("Thread " + Thread.currentThread().getName() 
                      + " interrupted, reason " + e.getMessage());
          throw new RuntimeException("Thread interrupted", e);
        }
      }
    }
  }
  public static void main(String[] args) {
    InterruptDemo id = new InterruptDemo();
    Thread t1 = new Thread(id);
    Thread t2 = new Thread(id);
    //long startTime = System.currentTimeMillis();
    t1.start();
    t2.start();
  }
}
Output
Thread-0 Value - 0
Thread-0 Value - 1
Thread-0 Value - 2
Thread-1 Value - 0
Thread-1 Value - 1
Thread-1 Value – 2

As you can see when sleep() method is called with in the synchronized context thread is not giving up the object’s monitor. From the output you can see there is no interleaving between the threads once one of the thread finishes and releases the lock then only another thread enters the synchronized block.

That's all for the topic Difference Between sleep() And wait() Methods in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment