Wednesday, February 15, 2023

Difference between wait and sleep in Java Thread? Example

Wait vs sleep in Java
Differences between wait and sleep methods in Java multi-threading is one of the very old questions asked in Java interviews. Though both wait and sleep put the thread on waiting for state, they are completely different in terms of behavior and use cases. Thread.sleep(long millis) is meant for introducing pause, releasing CPU, and giving another thread an opportunity to execute while wait is used for inter-thread communication in Java. These methods are defined in java.lang.Object class and available to every object in Java. It is based upon object lock, if you remember every object in Java has an implicit lock, also known as a monitor.

When a thread enters into a synchronized method it acquired the lock which is used to protect the critical reason e.g. it acquired lock on the current object if it is going inside an instance synchronized method and lock object on class literal if it's entering into a static synchronized method.

By using the wait() and notify() method two threads can communicate with each other which is key to solve many concurrency problems like produce consumer problems, dining philosopher problems, reader and writer problems, and implementing several Concurrency designs.

In this tutorial, you will learn about following this about wait() and sleep() method in Java :
  • What is the wait() method in Java?
  • What is the sleep() method in Java?
  • What is the difference between wait and sleep in Java?
  • Where to use wait and sleep in Java?
By the way, if you are preparing for a Java interview then I suggest you take a look at these Java Interview preparation courses which contain a lot of great resources, tailored for Java interviews.




What is the wait and sleep method in Java?

The wait() method is defined in the Object class and it is available to all objects, wait() method is always discussed along with its counterpart notify() and notifyAll() method and is used in inter-thread communication in Java.

The wait() method puts a thread on wait by checking some conditions like in Producer-Consumer problem, producer thread should wait if Queue is full or Consumer thread should wait if Queue is empty.

The notify() method is used to wake up waiting for the thread by communicating that the waiting condition is over now for example once the producer thread puts an item on an empty queue it can notify the Consumer thread that Queue is not empty anymore. On the other hand sleep() method is used to introduce pause on Java applications.

You can put a Thread on sleep, where it does not do anything, and relinquish the CPU for a specified duration. When a Thread goes to Sleep it can be either wake up normally after sleep duration elapsed or it can be woken up abnormally by interrupting it.





Difference between Wait and Sleep method in Java Thread

In the last section, we saw what is wait and sleep method and in this section, we will see what are differences between wait and sleep methods in Java. As I told before apart from waiting they are completely different from each other:


1. Synchronized Context
The first and most important difference between the Wait and sleep methods is that the wait method must be called from a synchronized context i.e. from a synchronized method or block in Java. If you call the wait method without synchronization, it will throw IllegalMonitorStateException in Java. On the other hand, there is no requirement of synchronization for calling sleep method, you can call it normally.


2. Location
Second worth noting difference between the wait and sleep method is that, wait operates on Object and is defined in Object class while sleep operates on current Thread and is defined in java.lang.Thread class.


3. Lock Acquisition and Release
The third and significant difference between wait and sleep in Java is that the wait() method releases the lock of the object on which it has called, it does release other locks if it holds any while the sleep method of the Thread class does not release any lock at all.


4. Calling Mechanism
The wait method needs to be called from a loop in order to deal with false alarms like waking even though the waiting condition still holds true, while there is no such thing as the sleep method in Java. it's better not to call the Sleep method from the loop.

here is the code snippet for calling the wait and sleep method in Java

synchronized(monitor)
while(condition == true){ monitor.wait())  //releases monitor lock

Thread.sleep(100); //puts current thread on Sleep



5. Static vs non-static method
One more difference between the wait and sleep methods which is not as significant as the previous ones is that wait() is a non-static method while sleep() is a static method in Java. You can also see these Java thread courses to learn more about essential multithreading concepts like lock and synchronization. 

Difference between wait() and sleep() method in Java?




Where to use the wait and sleep method in Java?

By reading the properties and behavior of the wait and sleep method it's clear that the wait() method should be used in conjunction with notify() or notifyAll() method and intended for communication between two threads in Java while Thread.sleep() method is a utility method to introduce short pauses during program or thread execution. 

Given the requirement of synchronization for the wait, it should not be used just to introduce pause or sleep in Java.


In summary wait and sleep, methods are completely different from each other and have different use cases. Use wait() and notify() method for inter-thread communication while use sleep() method for introducing small pause during thread execution. 

Also remember, that wait() method will release the lock acquired when it entered into synchronized block or method, but sleep() method will keep the lock with itself. So if your design requires releasing the lock during the waiting period then use the wait() and notify method otherwise just use sleep().

Other Java Concurrency and Multithreading tutorials You may like
If you like this tutorial and are interested in a couple of more multi-threading interview questions and their detailed answer then you might enjoy the following articles as well :
  • What is the difference between Runnable and Callable interfaces in Java? (answer)
  • 50 Java Thread Questions for interviews (thread questions)
  • Which is better, extends Thread or implements Runnable? (answer)
  • Difference between atomic, synchronized, and volatile in java? (volatile vs synchronized)
  • What is the difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • My favorite free Java Multithreading courses for beginners (free concurrency courses)
  • What is the difference between Thread and Process in Java? (answer)
  • My favorite books to learn Concurrency programming in Java (threading books)
  • When to use notify() and notifyAll() methods in Java? (answer)
  • What is the difference between the wait() and yield() method in Java? (answer)
  • Difference between synchronized ArrayList vs CopyOnWriterArrayList in Java? (answer)
Thanks for reading this article so far. If you find this article useful then please share it with your friends and colleagues on Twitter, Facebook, and LinkedIn. You can find sharing buttons below.


P. S. - If you wan to learn Java Multithreading in depth and looking for resources then you can also checkout this list of best Java Concurrency and Multithreading Courses for experienced developers. It contains best courses to learn Java threads in depth. 


9 comments:

  1. Great comparison between wait vs sleep but isn't comparing wait() with sleep() is like comparing Oranges with Apple ?

    ReplyDelete
    Replies
    1. Why, Apple and Oranges, isn't it both stop thread from further processing? or both paused current thread. I agree on intent though, since wait is clearly for a condition, i..e wait until certain condition is true, while sleep() is just a momentary pause i.e. sleep for 100 ms etc.

      Delete
  2. Excellent Comparison ...

    ReplyDelete
  3. Very good explanation.

    ReplyDelete
  4. Thread.sleep(long millis) is meant for introducing pause, releasing CPU and giving another thread an opportunity to execute....
    IS THIS CORRECT?

    ReplyDelete
    Replies
    1. Yes, that's correct but more importantly it doesn't release the lock.

      Delete

Feel free to comment, ask questions if you have any doubt.