What is difference between sleep() and wait() method in Java?

Carvia Tech | April 23, 2019 at 09:56 AM | 13 views | Multithreading and Concurrency


wait() and notify() are used in multi-threading programming for inter-thread communication, while sleep is used to control execution time of current thread.

Summary of difference b/w sleep() and wait()

  1. sleep() method is part of java.lang.Thread class

    private void sleepExample()
      throws InterruptedException {
        Thread.sleep(1000);
      }

    wait() is method of Object class, though Thread class also has wait() method since it inherits from Object too, but wait() is called on the synchronized object.

    Object lock = new Object();
    synchronized (lock) {
        lock.wait();
    }
  2. sleep() may be called from anywhere. wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException

  3. sleep() does not release the lock acquired by thread on current object. wait() releases the lock on object waiting for a condition to be fulfilled, in the meantime another thread can acquire the lock on this object.

  4. sleeping thread can not be woken up (except by calling Thread.interrupt()). A wait can be "woken up" by another thread calling notify() or notifyAll() on the monitor which is being waited. If more than one thread are waiting on the given object, only one of them will be able to grab the lock.

    synchronized (lock) {
        lock.notifyAll();
    }
  5. spurious wakeups (waiting thread wakes up for no apparent reason) can happen on wait(), so you should always call wait() inside a while loop on some condition.

    synchronized (lock) {
        while (!condition) {
         lock.wait();
        }
        //Take action
    }

    Such wakeups never happen in sleep().

  6. Thread goes from Runnable to TIMED_WAITING state. Thread goes from Runnable to WAITING state, if no timeout is specified

The below example of CustomSemaphore illustrates use of wait() and notify() method on a object monitor in synchronized context.

Custom Semaphore using wait() and notify()
public class CustomSemaphore {
    private final Object monitor = new Object();
    private int permits;

    CustomSemaphore(int initialPermits) {
        synchronized (monitor) {
            permits = initialPermits;
        }
    }

    /**
     * Blocks until permitsAvailable (permit > 0)
     */
    public void acquire() throws InterruptedException {
        synchronized (monitor) {
            while (permits <= 0)
                monitor.wait();
            --permits;
        }
    }

    /**
     * Release a single permit and notifies threads waiting on permitsAvailable Condition
     */
    public void release() {
        synchronized (monitor) {
            ++permits;
            monitor.notifyAll();
        }
    }
}

In general, we should use sleep() for controlling execution time of one thread and wait() & notify() for multi-thread synchronization.


Top articles in this category:
  1. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
  2. Difference between Implementing Runnable and Extending Thread
  3. What is difference between Vector and ArrayList, which one shall be preferred
  4. Can two threads call two different synchronized instance methods of an Object?
  5. What is difference between Callable and Runnable Interface?
  6. Difference between Comparable and Comparator in Java
  7. What is difference between JDK JRE and JVM


Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 month ago


Recommended books for interview preparation:
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Spring Microservices Interviews for Java Developers
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.5 by Munish Chandel

This website uses cookies to ensure you get the best experience on our website. more info