๐ Understanding wait() and notify() in Java (with Example)
In multithreaded programming, thread coordination is often needed when multiple threads work on the same shared resource.
In Java, this coordination is achieved using the wait() and notify() methods from the Object class.
⚙️ What Are wait() and notify()?
๐ wait()
-
Causes the current thread to pause its execution and release the lock on the object it’s holding.
-
The thread stays in the waiting state until another thread calls
notify()ornotifyAll()on the same object. -
Must be called inside a synchronized block.
๐ notify()
-
Wakes up one thread that is waiting on the same object’s monitor.
-
The awakened thread will compete to reacquire the lock and continue execution.
๐ก Important:
Bothwait()andnotify()must be used inside synchronized blocks or methods, otherwise ajava.lang.IllegalMonitorStateExceptionwill be thrown.
๐งฉ Example — Coordinating Two Threads Using wait() and notify()
In the below example:
-
Two threads share the same
ArrayListresource. -
removeRecordthread waits until there’s data to remove. -
addRecordthread adds a record and then notifies the waiting thread to continue.
๐ป Java Code
๐งพ Example Output
๐ง Step-by-Step Explanation
๐งฉ Text-Based Visualization
At any given time:
-
Only one thread holds the lock on the shared resource (
students). -
The
wait()call temporarily releases that lock. -
The
notify()call signals another waiting thread to resume once the lock becomes available.
๐งฑ Key Points to Remember
| Method | Description |
|---|---|
wait() | Pauses the current thread and releases the lock |
notify() | Wakes up one waiting thread on the same object |
notifyAll() | Wakes up all threads waiting on the same object |
Must use inside synchronized | Required for thread safety and correct monitor behavior |
| Common use case | Producer–Consumer and resource coordination patterns |
⚠️ Common Mistakes to Avoid
-
❌ Calling
wait()ornotify()outside a synchronized block → throwsIllegalMonitorStateException. -
❌ Forgetting to handle
InterruptedException. -
❌ Not checking condition again after
wait()(always recheck the condition in a loop in real applications). -
❌ Using shared resource without proper synchronization → causes data inconsistency.
✅ Best Practice
In real-world scenarios, always use a while loop around wait() to handle spurious wake-ups:
This ensures that the thread only proceeds when the condition is actually met.
No comments:
Post a Comment