Table of contents
1.
Introduction
2.
wait() Method
2.1.
1. wait()
2.2.
2. wait(long timeout)
2.3.
3. wait(long timeout, int nanos)
3.
notify() Method
4.
Differences between wait() & notify()
5.
 
6.
 
7.
 
8.
 
9.
Various Exceptions
9.1.
1. wait()
9.2.
2. notify()
10.
Frequently Asked Questions
10.1.
Can I call wait() or notify() methods without synchronization?
10.2.
What happens if multiple threads are waiting on the same object and notify() is called?
10.3.
Can I use wait() and notify() methods with any object?
11.
Conclusion
Last Updated: Aug 14, 2024
Easy

wait() and notify() in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java programming, thread synchronization is a crucial concept that every developer should learn. Two essential methods that play a vital role in thread synchronization are wait() & notify(). These methods allow threads to communicate & coordinate their actions, which ensures proper execution & avoiding conflicts. 

wait() and notify() in Java

In this article, we will discuss the wait() & notify() methods in Java, and understand their use, variations, & differences.

wait() Method

The wait() method is used to pause the execution of a thread until another thread notifies it to resume. When a thread calls the wait() method, it releases the lock it holds on the synchronized object and enters a waiting state. The thread remains in the waiting state until another thread calls the notify() or notifyAll() method on the same synchronized object.

The wait() method has three variations:

1. wait()

This is the simplest form of the wait() method. It causes the calling thread to wait indefinitely until another thread calls the notify() or notifyAll() method on the same object.

synchronized (obj) {
    try {
        obj.wait();
    } catch (InterruptedException e) {
        // Handle the exception
    }
}

2. wait(long timeout)

This variation of the wait() method allows you to specify a timeout period in milliseconds. The calling thread waits until either another thread notifies it or the specified timeout period elapses.

synchronized (obj) {
    try {
        obj.wait(5000); // Wait for 5 seconds
    } catch (InterruptedException e) {
        // Handle the exception
    }
}

3. wait(long timeout, int nanos)

This variation is similar to wait(long timeout) but allows you to specify an additional nanosecond value for more precise timeout control.

synchronized (obj) {
    try {
        obj.wait(5000, 100); // Wait for 5 seconds and 100 nanoseconds
    } catch (InterruptedException e) {
        // Handle the exception
    }
}


It's important to note that the wait() method can only be called within a synchronized block or method. If it is called outside of a synchronized context, an IllegalMonitorStateException will be thrown.

notify() Method

The notify() method is used to wake up a single thread that is waiting on the same synchronized object. When a thread calls the notify() method, it selects one of the waiting threads and notifies it to resume execution. The choice of which thread to notify is arbitrary and depends on the implementation of the Java Virtual Machine (JVM).

For example : 

synchronized (obj) {
    // Perform some operations
    obj.notify(); // Notify a waiting thread
}


It's important to note that the notify() method does not release the lock on the synchronized object immediately. The notifying thread continues to hold the lock until it exits the synchronized block or method, or until it calls the wait() method itself.

In some cases, you may want to wake up all the threads waiting on the synchronized object instead of just one. For this purpose, you can use the notifyAll() method, which notifies all the waiting threads.

synchronized (obj) {
    // Perform some operations
    obj.notifyAll(); // Notify all waiting threads
}


Both notify() and notifyAll() methods should be called within a synchronized block or method to avoid an IllegalMonitorStateException.

Differences between wait() & notify()

Aspect

wait()

notify()

PurposeMakes a thread wait until it is notified by another threadWakes up a single waiting thread
ExecutionReleases the lock on the synchronized object and enters a waiting stateNotifies one of the waiting threads to resume execution
Lock ReleaseThe waiting thread releases the lock when it calls wait()The notifying thread continues to hold the lock until it exits the synchronized block or calls wait()
Notification ScopeUsed when a thread needs to wait for a specific condition to be metUsed to signal a waiting thread that the condition it was waiting for has been met
Thread SelectionWhen multiple threads are waiting, the choice of which thread to notify is arbitrary and depends on the JVM implementationWakes up a single thread, chosen arbitrarily by the JVM

 

 

 

 

 

.

Various Exceptions

When working with wait() and notify() methods, it's important to be aware of the exceptions that can occur. 

Let’s discuss some common exceptions associated with these methods:

1. wait()

   - InterruptedException: This exception is thrown when a waiting thread is interrupted by another thread. It is a checked exception, which means it must be handled explicitly using a try-catch block or declared in the method signature.

 Example

   synchronized (obj) {
       try {
           obj.wait();
       } catch (InterruptedException e) {
           // Handle the exception
       }
   }


   - IllegalMonitorStateException: This exception is thrown when the wait() method is called on an object that is not locked by the calling thread. It occurs when wait() is invoked outside of a synchronized context.

Example

   // Incorrect usage
   obj.wait(); // Throws IllegalMonitorStateException

2. notify()

   - IllegalMonitorStateException: Similar to wait(), this exception is thrown when the notify() method is called on an object that is not locked by the calling thread. It occurs when notify() is invoked outside of a synchronized context.

 Example

   // Incorrect usage
   obj.notify(); // Throws IllegalMonitorStateException


To avoid these exceptions, make sure to:

- Call wait() and notify() methods only within synchronized blocks or methods.

- Handle the InterruptedException when using wait() by either catching it or declaring it in the method signature.

- Ensure that the thread calling wait() or notify() holds the lock on the synchronized object.

Frequently Asked Questions

Can I call wait() or notify() methods without synchronization?

No, wait() and notify() methods must be called within a synchronized block or method to avoid an IllegalMonitorStateException.

What happens if multiple threads are waiting on the same object and notify() is called?

When multiple threads are waiting on the same object and notify() is called, only one thread is notified and woken up. The choice of which thread to notify is arbitrary and depends on the JVM implementation.

Can I use wait() and notify() methods with any object?

Yes, wait() and notify() methods can be called on any object in Java. However, it is recommended to use them with objects that serve as locks for synchronization purposes.

Conclusion

In this article, we have discussed the wait() and notify() methods in Java, which are important for thread synchronization. We learned about the different variations of the wait() method and how to use them to make a thread wait until notified. We also explained the notify() method and its role in waking up waiting threads. At last, we talked about the main differences between wait() and notify() methods and the exceptions that can occur when using them.

You can also check out our other blogs on Code360.

Live masterclass