How to use wait and notify in Java without IllegalMonitorStateException?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Java provides a robust and flexible mechanism for managing multithreading through synchronization. Among the tools at your disposal are the wait(), notify(), and notifyAll() methods, which are essential for coordinating access to shared resources. However, improper use of these methods can lead to runtime exceptions, particularly the IllegalMonitorStateException. This article explains how to use these methods effectively, avoiding common pitfalls.
Understanding the Basics
Monitor and Synchronization
In Java, every object has an intrinsic lock known as a monitor. The wait(), notify(), and notifyAll() methods are designed to be used within synchronized blocks or methods that synchronize on the object's monitor. This ensures orderly access to the resource and prevents race conditions.
Common Pitfall: IllegalMonitorStateException
This exception is typically thrown when a thread attempts to call wait(), notify(), or notifyAll() without holding the appropriate lock on the object’s monitor. The following sections describe how to correctly use these methods to avoid this exception.
How to Use wait() and notify()
Step 1: Acquire the Monitor
Before you can call wait() or notify(), you must first acquire the monitor lock on the object you are synchronizing on. This is done by using a synchronized block or method.
Step 2: Use wait()
The wait() method causes the current thread to wait until another thread invokes notify() or notifyAll() on the same object. It is crucial that wait() is called within the block that has already acquired the object's monitor.
Step 3: Use notify()
The notify() method wakes up a single thread that is waiting on the object’s monitor. This method should also be called within a synchronized block.
Example: Producer-Consumer Problem
Here's an example demonstrating the correct use of wait() and notify() in the classic Producer-Consumer problem.
Key Points and Summary Table
The following table summarizes the key points when using wait() and notify():
| Key Point | Description |
| Synchronization | Always use wait() and notify() inside a synchronized block. |
| Object Lock | Acquire the monitor of the object you are using wait() on. |
| Handling Exceptions | Use try-catch around wait() to handle InterruptedException. |
Precise Use of notify() | Only call notify() after making a meaningful change in the object state. |
Avoiding IllegalMonitorStateException | Ensure that the current thread holds the monitor before calling wait() or notify(). |
Additional Tips
- Use
notifyAll(): When possible, prefernotifyAll()if multiple threads may be waiting, to avoid missing wake-up signals. - Recheck Conditions: Always recheck your condition in a loop after waking up, as
interrupt()or spurious wake-ups can happen. - Atomic Operations: Ensure that the operations between
wait()andnotify()are as small and quick as possible to reduce the lock contention.
With these guidelines and examples, you should be able to effectively use wait(), notify(), and notifyAll() in Java without encountering IllegalMonitorStateException. Understanding the importance of the object's monitor in the context of these methods is critical for synchronized thread communication.
Related reading
- How to use WPF Background Worker
- How to wait all spawned async tasks
- How to wait for a async void method to complete its task?
- How to wait for a BackgroundWorker to cancel?
- How to use WeakReference in Java and Android development?
- How to use WebClient to execute synchronous request?
- How to wait for a BackgroundWorker to cancel?
- How to wait for a JavaScript Promise to resolve before resuming function?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.