Sunday, July 18, 2021

Difference Between sleep And wait in Java Multi-Threading

Difference between sleep() and wait() methods in Java is a popular Java multi-threading interview question. It is another confusing question just like Difference between yield and sleep because functionality wise both sleep() and wait() look quite similar.

When sleep method is called with a specified time, currently executing thread goes in a TIMED_WAITING state.

Same way when wait method is called on an object the thread currently holding the lock on that object goes in a waiting state (or TIMED_WAITING state depending upon which of the three wait methods is being called).

Since both sleep() and wait() methods when called put the currently executing thread in a waiting state then what exactly is the difference between sleep() and wait() methods in Java, that's what we'll try to find here.

sleep() Vs wait() methods in Java multi-threading

  1. The very first difference is that sleep() is defined as a static method in Thread class and operates on the currently executing thread.
    Whereas wait() method is in Object class and operates on the thread which is currently holding the lock on the object on which the wait method is called.
  2. Since wait method is supposed to release the lock on an object so it has to be called from a synchronized context (with in a synchronized method or synchronized block). Not calling wait() method from a synchronized context will result in a IllegalMonitorStateException being thrown.
    With sleep method there is no such mandatory condition. It doesn't need to be called from a synchronized context.
  3. wait() method releases the lock it holds on an object before going to waiting state which gives another thread a chance to enter the synchronized block.
    sleep() method, if called from a synchronized block or method, will not release the lock so another thread won't get a chance to enter the synchronized block.
  4. When wait() method is called upon an object the thread which is currently holding the lock on that object goes to waiting state and it changes state to runnable only when the notify() or notifyAll() method is called by some thread on the same object.

    There are overloaded wait() methods too

       public final void wait(long timeout) throws InterruptedException
       
    And
      public final void wait(long timeout, int nanos) throws InterruptedException
    

    which causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

    In case of sleep() method thread changes state to runnable after the specified time is elapsed. As example Thread.sleep(4000); will make the currently executing thread to sleep for 4 seconds and thread is ready to run again when the specified time has elapsed . This sleep period can be terminated by interrupts.

Example of thread interrupt method

public class InterruptDemo extends Thread {
	@Override
	public void run(){  
		try {
			Thread.sleep(4000);
		} catch (InterruptedException Iexp) {
			System.out.println("Thread Interrupted exception "+ Iexp); 
		}
		 
		System.out.println("thread after interruption...");  
	}  
	public static void main(String[] args) {        
		InterruptDemo thread1 = new InterruptDemo();
		thread1.start();
		thread1.interrupt();
	}
}

Output

Thread Interrupted exception java.lang.InterruptedException: sleep interrupted
thread after interruption...

That's all for this topic Difference Between sleep And wait in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. isAlive() & join() Methods in Java Multi-Threading
  2. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  3. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
  4. Deadlock in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Polymorphism in Java
  2. How HashMap Internally Works in Java
  3. Lock Striping in Java Concurrency
  4. Difference Between CountDownLatch And CyclicBarrier in Java
  5. How to Convert Date And Time Between Different Time-Zones in Java
  6. How to Create Immutable Class in Java
  7. Difference Between throw And throws in Java
  8. How to Inject Prototype Scoped Bean in Singleton Bean

No comments:

Post a Comment