Difference between sleep and wait in java

Table of Contents

One of the common interview question is “What is difference between sleep and wait in java”.Before we actually see differences,let me give you brief introduction of both.

sleep

  • It causes current executing thread to sleep for specific amount of time.
  • Its accuracy depends on system timers and schedulers.
  • It keeps the monitors it has acquired, so if it is called from synchronized context, no other thread can enter that block or method.
  • If we call interrupt() method , it will wake up the sleeping thread.

wait

  • It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object
  • It must be called from synchronized context i.e. from block or method.It means before wait() method is called,current thread must have lock on that object.
  • It releases lock on the object on which it is called and added to wait list, so another thread can acquire lock on the object.

sleep vs wait:

Parameter
wait
sleep
Synchonized

wait should be called from synchronized context i.e. from block or method, If you do not call it using synchronized context, it will throw IllegalMonitorStateException

It need not be called from synchronized block or methods
Calls on

wait method operates on Object and defined in Object class

Sleep method operates on current thread and is in java.lang.Thread
Release of lock
wait release lock of object on which it is called and also other locks if it holds any
Sleep method does not release lock at all
Wake up condition
until call notify() or notifyAll() from Object class
Until time expires or calls interrupt()
static
wait is non static method
sleep is static method

You can go through core java interview questions for beginners and experienced for more such questions.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *