Difference Between wait() and notify() in Java
Last Updated :
04 Apr, 2022
The wait() and notify() are methods of the Object class. They were introduced to part ways with polling, which is the process of repeatedly checking for a condition to be fulfilled. Polling wastes CPU resources considerably, hence it is not preferred.
wait() Method
wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread.
The wait() method has 3 variations:
1. wait(): This is a basic version of the wait() method which does not take any argument. It will cause the thread to wait till notify is called.
public final void wait()
2. wait(long timeout): This version of the wait() method takes a single timeout argument. It will cause the thread to wait either till notify is called or till timeout (One which occurs earlier).
public final void wait(long timeout)
3. wait(long timeout, int nanoseconds): This version of the wait() method takes a timeout argument as well as a nanosecond argument for extra precision.
public final void wait(long timeout, int nanoseconds)
notify() Method
The notify() method is defined in the Object class, which is Java's top-level class. It's used to wake up only one thread that's waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread.
public final void notify()

Differences between wait() and notify()
S. No. | Wait() | notify() |
---|
1. | When wait() is called on a thread holding the monitor lock, it surrenders the monitor lock and enters the waiting state. | When the notify() is called on a thread holding the monitor lock, it symbolizes that the thread is soon going to surrender the lock. |
2. | There can be multiple threads in the waiting state at a time. | One of the waiting threads is randomly selected and notified about the same. The notified thread then exits the waiting state and enters the blocked state where it waits till the previous thread has given up the lock and this thread has acquired it. Once it acquires the lock, it enters the runnable state where it waits for CPU time and then it starts running.
|
3. | The wait() method is defined in the Object class | The notify() method is defined in the Object class |
4. | The wait() method is used for interthread communication. | The notify() method is used to wake up a single thread |
5. | The wait() method is a part of java.lang.Object class | The notify() method does not have any return type value |
6. | The wait() method is tightly integrated with the synchronization lock | The notify() method is used to give the notification for one thread for a particular object |
Below is demonstration of wait() and notify() method:
Java
// Java Program to demonstrate usage of wait() and notify()
class demo {
// variable to check if part1 has returned
// volatile used to prevent threads from
// storing local copies of variable
volatile boolean part1done = false;
// method synchronized on this
// i.e. current object of demo
synchronized void part1()
{
System.out.println("Welcome to India");
part1done = true;
System.out.println(
"Thread t1 about to surrender lock");
// notify the waiting thread, if any
notify();
}
// method synchronized on this
// i.e. current object of demo
synchronized void part2()
{
// loop to prevent spurious wake-up
while (!part1done) {
try {
System.out.println("Thread t2 waiting");
// wait till notify is called
wait();
System.out.println(
"Thread t2 running again");
}
catch (Exception e) {
System.out.println(e.getClass());
}
}
System.out.println("Do visit Taj Mahal");
}
}
public class Main {
public static void main(String[] args)
{
// Make an instance of demo class
demo obj = new demo();
// Thread t1 will call part1()
Thread t1 = new Thread(new Runnable() {
public void run() { obj.part1(); }
});
// Thread t2 will call part2()
Thread t2 = new Thread(new Runnable() {
public void run() { obj.part2(); }
});
// Start t2 and then t1
t2.start();
t1.start();
}
}
OutputThread t2 waiting
Welcome to India
Thread t1 about to surrender lock
Thread t2 running again
Do visit Taj Mahal
Various Exceptions:
1. wait()
- It is mandatory to enclose wait() in a try-catch block because if a thread present in the waiting state gets interrupted, then it will throw InterruptedException.
- The other two variations of wait housing parameters will throw IllegalArgumentException if the value of timeout is negative or the value of nanoseconds is not in the range 0 to 9,99,999.
Below is the implementation for the exception handling.
Java
// Program demonstrating occurrence of InterruptedException
class demo {
volatile boolean part1done = false;
synchronized void part1()
{
System.out.println("Welcome to India");
part1done = true;
// notify() has been commented, waiting
// thread remains waiting forever notify();
}
synchronized void part2()
{
while (!part1done) {
try {
wait();
}
catch (Exception e) {
System.out.println("Exception : "
+ e.getClass());
// quit program after exception is thrown
System.exit(-1);
}
}
System.out.println("Do visit Taj Mahal");
}
}
public class Main {
public static void main(String[] args)
{
// Make an instance of demo class
demo obj = new demo();
// Thread t1 will call part1()
Thread t1 = new Thread(new Runnable() {
public void run() { obj.part1(); }
});
// Thread t2 will call part2()
Thread t2 = new Thread(new Runnable() {
public void run() { obj.part2(); }
});
// Start t2 and then t1
t2.start();
t1.start();
// This is a counter which will
// interrupt Thread t2 after 3 seconds
long startTime = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - startTime
> 3000)
t2.interrupt();
}
}
}
OutputWelcome to India
Exception : class java.lang.InterruptedException
2. notify()
Unlike wait(), the notify method does not throw an InterruptedException hence it is not mandatory to house it inside a try-catch block
Note:
- wait() and notify() both have a tendency to throw IllegalMonitorStateException
- This occurs when a thread is holding the monitor lock of object A and tries to call wait or notify on object B.
- In all the preceding examples, the methods were synchronized on "this" i.e. the object used to call those methods (obj). Also, the wait() & notify() were being called as this.wait() and this.notify() (usage of this was redundant). Hence, there was no issue.
- In the below example, the methods part1 and part2 are now synchronized on an Integer object, but wait() & notify() are still being called on the object which called these methods (obj).
- This causes an IllegalMonitorStateException
Below is the implementation of the exception handling.
Java
// Program to demonstrate IllegalMonitorStateException
class demo {
volatile boolean part1done = false;
// Made an Integer object a
// and set it randomly to 5
Integer a = 5;
void part1()
{
// Synchronized code on a
synchronized (a)
{
System.out.println("Welcome to India");
part1done = true;
// calling this.notify()
notify();
}
}
void part2()
{
// Synchronized code on a
synchronized (a)
{
while (!part1done) {
try {
// calling this.wait()
wait();
}
catch (Exception e) {
System.out.println("Exception: "+e.getClass());
System.exit(-1);
}
}
System.out.println("Do visit Taj Mahal");
}
}
}
public class Main {
public static void main(String[] args)
{
// Make an instance of demo class
demo obj = new demo();
// Thread t1 will call part1()
Thread t1 = new Thread(new Runnable() {
public void run() { obj.part1(); }
});
// Thread t2 will call part2()
Thread t2 = new Thread(new Runnable() {
public void run() { obj.part2(); }
});
// Start t2 and then t1
t2.start();
t1.start();
}
}
OutputException: class java.lang.IllegalMonitorStateException
Note: To fix the above code, just replace notify() with a.notify() on line 17 and wait() with a.wait() on line 29.
Similar Reads
Difference Between wait() and notifyall() in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Multi-threaded programs may often come to a situation where multi
7 min read
Difference Between notify() and notifyAll() in Java
The notify() and notifyAll() methods with wait() methods are used for communication between the threads. A thread that goes into waiting for state by calling the wait() method will be in waiting for the state until any other thread calls either notify() or notifyAll() method on the same object. not
6 min read
Difference between wait and sleep in Java
Sleep(): This Method is used to pause the execution of current thread for a specified time in Milliseconds. Here, Thread does not lose its ownership of the monitor and resume's it's execution Wait(): This method is defined in object class. It tells the calling thread (a.k.a Current Thread) to wait u
2 min read
Differences between wait() and join() methods in Java
The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution. wait() is mainly used for shared resources, a thread notifies other waiting thread when a resou
2 min read
Difference Between sleep and yield Method in Java
In java if a thread doesn't want to perform any operation for a particular amount of time then we should go for the sleep() method, which causes the currently executing thread to stop for the specified number of milliseconds. Syntax : public static native void sleep( long ms) throws InterruptedExcep
4 min read
Difference between volatile and transient keywords in Java
Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. Before getting into the differences, let us first understand what each of them actually means.
3 min read
Difference Between Java Threads and OS Threads
In modern computing, multitasking and parallel processing are essential for improving system performance. Two important concepts that enable this are Java Threads and Operating System (OS) Threads. Both play a key role in managing concurrent tasks, but they operate at different levels and interact w
8 min read
Difference Between Callable and Runnable in Java
java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread â Subclass Thread and implement Runnable. There is no need of sub-classing Thread when a task can be done by overriding only run()
3 min read
Difference Between Lock and Monitor in Java Concurrency
Java Concurrency deals with concepts like Multithreading and other concurrent operations. To manage shared resources effectively, tools like Locks (Mutex) and Monitors are used to ensure thread synchronization and avoid race conditions. Locks represent a low-level synchronization mechanism and Monit
5 min read
Difference Between Mutex and Monitor in OS
Pre-requisites: Monitors in Process Synchronization In the field of Computer Science and OS, Mutex, and Monitor are most of the important fundamental mechanisms which are synchronization used for managing the concurrent access of different shared resources by a number of threads and processes. The m
4 min read