Introduction
Java provides powerful multithreading capabilities that allow multiple threads to execute concurrently. In many multithreaded applications, threads need to communicate with each other while sharing resources. Instead of continuously checking whether a resource is available, Java provides Inter-Thread Communication methods such as wait(), notify(), and notifyAll().
The notifyAll() method is used to wake up all threads that are waiting on the monitor (lock) of a particular object. Unlike notify(), which wakes only one waiting thread, notifyAll() ensures that every waiting thread gets a chance to compete for the object’s lock and continue execution when appropriate.
The notifyAll() method is defined in the Object class, meaning every Java object inherits it. Since it operates on an object’s monitor, it must always be called from within a synchronized method or synchronized block.
What is Java notifyAll()?
The notifyAll() method wakes up all threads that are waiting on the monitor of an object.
When several threads have called wait() on the same object, they enter the WAITING state. Calling notifyAll() moves all of those waiting threads to the RUNNABLE state. However, only one thread can acquire the object’s monitor at a time, so each awakened thread must compete to obtain the lock before it can continue execution.
Threads that fail to acquire the monitor immediately remain blocked until the lock becomes available.
Syntax
public final void notifyAll()
Important Points
- Defined in the Object class.
- Wakes all threads waiting on the same object.
- Must be called inside a synchronized method or synchronized block.
- Does not immediately release the monitor lock.
- Throws IllegalMonitorStateException if the current thread does not own the object’s monitor.
How notifyAll() Works
The following steps explain how notifyAll() operates:
- One or more threads enter a synchronized block.
- They call wait() and release the object’s monitor.
- These threads enter the WAITING state.
- Another thread acquires the same monitor.
- It performs the required work.
- It calls notifyAll().
- All waiting threads become runnable.
- The notifying thread exits the synchronized block.
- Each awakened thread competes for the monitor lock.
- Threads continue execution one by one after acquiring the lock.
This approach ensures that every waiting thread has an opportunity to proceed when the shared state changes.
Basic Example of notifyAll()
class Shared {
synchronized void waitForSignal() {
System.out.println(Thread.currentThread().getName() + " is waiting");
try {
wait();
} catch (InterruptedException e)
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " resumed");
}
synchronized void sendSignal() {
System.out.println("Sending notification to all threads");
notifyAll();
}
}
public class Demo
public static void main(String[] args) {
Shared shared = new Shared();
Thread t1 = new Thread(() -> shared.waitForSignal(), "Thread-1");
Thread t2 = new Thread(() -> shared.waitForSignal(), "Thread-2");
Thread t3 = new Thread(() -> shared.waitForSignal(), "Thread-3");
t1.start();
t2.start();
t3.start();
try {
Thread.sleep("1111");
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(shared::sendSignal).start();
}
}
Possible Output
Thread-2 is waiting
Thread-3 is waiting
Sending notification to all threads
Thread-2 resumed
Thread-1 resumed
Thread-3 resumed
The order in which threads resume is not guaranteed because it depends on the JVM scheduler.
Example with Producer and Consumer
class Buffer {
private boolean available = false;
synchronized void produce() {
available = true;
System.out.println("Item Produced")
notifyAll();
}
synchronized void consume() {
while (!available)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Item Consumed");
available = false;
}
}
In this example:
- Consumer threads wait until an item becomes available.
- The producer creates an item.
- notifyAll() wakes every waiting consumer.
- Only one consumer acquires the lock first, while others wait again if the condition is no longer satisfied.
This demonstrates why waiting conditions should always be checked inside a while loop.
notifyAll() vs notify()
| Feature | notify() | notifyAll() |
|---|---|---|
| Threads Awakened | One | All |
| Performance | Faster | Slightly slower |
| Lock Competition | One thread | All waiting threads |
| Best For | Single waiting thread | Multiple waiting threads |
| Risk of Missed Notification | Higher | Lower |
notifyAll() vs wait()
| Feature | wait() | notifyAll() |
|---|---|---|
| Purpose | Makes a thread wait | Wakes all waiting threads |
| Releases Lock | Yes | No |
| Thread State | WAITING | Waiting threads become RUNNABLE |
| Synchronization Required | Yes | Yes |
| Defined In | Object | Object |
notifyAll() vs Thread.sleep()
| Feature | notifyAll() | nThread.sleep() |
|---|---|---|
| Purpose | Wake waiting threads | Pause current thread |
| Releases Lock | No | No |
| Synchronization Required | Yes | No |
| Thread Communication | Yes | No |
Real-Life Example
Imagine passengers waiting at an airport boarding gate.
- Several passengers are waiting for boarding.
- The airline announces that boarding has started.
- Every passenger hears the announcement.
- All passengers move toward the boarding gate.
- Only a few passengers can enter the aircraft at a time.
This is similar to notifyAll().
- Waiting passengers = waiting threads.
- Boarding announcement = notifyAll().
- Boarding gate = monitor lock.
- Entering passengers = threads acquiring the lock one by one.
When Should You Use notifyAll()?
Use notifyAll() when:
- Multiple threads are waiting on the same object.
- Different threads are waiting for different conditions.
- You cannot safely determine which thread should continue.
- Multiple consumers or producers share the same resource.
- Avoiding missed notifications is more important than minimizing wakeups.
Common Use Cases
The notifyAll() method is commonly used in:
- Producer-Consumer applications
- Thread coordination
- Blocking queues
- Resource management
- Task scheduling
- Event-driven systems
- Thread pools
- Shared data synchronization
Common Mistakes
1. Calling notifyAll() Outside a Synchronized Block
Incorrect:
lock.notifyAll();
This throws:
IllegalMonitorStateException
Correct:
synchronized(lock) {
lock.notifyAll();
}
2. Using if Instead of while
Incorrect:
if (!ready)
wait();
}
Correct:
while (!ready) {
wait();
}
A while loop protects against spurious wakeups and ensures the shared condition is still true before proceeding.
3. Forgetting to Update the Shared Condition
Calling notifyAll() without updating the shared state causes awakened threads to immediately discover that they still cannot proceed and return to waiting.
4. Assuming Threads Resume in Order
notifyAll() does not guarantee the order in which awakened threads acquire the monitor. Scheduling depends on the JVM and operating system.
5. Replacing notifyAll() with notify()
When multiple waiting threads depend on different conditions, using notify() may awaken a thread that still cannot proceed, while the appropriate thread remains waiting. In such cases, notifyAll() is the safer choice.
Best Practices
- Always call notifyAll() inside synchronized code.
- Protect shared conditions with a while loop.
- Keep synchronized blocks short to reduce lock contention.
- Update the shared state before calling notifyAll().
- Use meaningful lock objects instead of synchronizing on arbitrary objects.
- Use notifyAll() when multiple waiting threads may be eligible to continue.
- Consider higher-level concurrency utilities from java.util.concurrent for complex synchronization requirements.
Conclusion
The Java notifyAll() method is a key part of Java’s inter-thread communication mechanism. It wakes every thread waiting on an object’s monitor, allowing each thread to compete for the lock and continue execution when the required condition is satisfied.
Compared to notify(), notifyAll() is generally the safer option in applications where multiple threads are waiting or where different conditions are involved. By combining wait(), notifyAll(), proper synchronization, and condition checks inside while loops, developers can build reliable, efficient, and thread-safe Java applications.
A solid understanding of notifyAll() is essential for mastering Java multithreading and is a common topic in Java interviews and real-world concurrent programming.