21/05/2025
What are volatile, wait(), notify(), and notifyAll()?
✅ volatile Keyword
Definition:
• volatile is a modifier used for variables that may be accessed by multiple threads.
Purpose:
• It tells the JVM not to cache the value of this variable and always read from the main memory.
• It ensures visibility, but not atomicity.
private volatile boolean flag = false;
This ensures that when one thread updates flag, other threads immediately see the updated value.
Use Case:
Used for flags or state variables shared across threads (e.g., stopping a thread).
✅ wait()
Definition:
• Causes the current thread to wait until another thread calls notify() or notifyAll() on the same object.
Key Points:
• Must be called from a synchronized block or method.
• It releases the monitor (lock) on the object, allowing other threads to acquire it.
synchronized(obj) {
obj.wait();
}
✅ notify()
Definition:
• Wakes up one thread that is waiting on the object’s monitor (from a wait() call).
Key Points:
• Like wait(), it must be used in a synchronized block.
• The awakened thread still needs to reacquire the object’s lock before continuing.
synchronized(obj) {
obj.notify();
}
✅ notifyAll()
Definition:
• Wakes up all threads waiting on the object’s monitor.
Use Case:
Used when multiple threads might be waiting and you want to notify all of them.
synchronized(obj) {
obj.notifyAll();
}
🔁 How They Work Together
In a producer-consumer problem:
• The consumer might wait() if the queue is empty.
• The producer adds items and calls notify() to wake up the consumer.
⸻
⚠️ Important Notes:
• wait(), notify(), and notifyAll() are methods of java.lang.Object, not Thread.
• You can’t call them on a Thread instance unless it’s inside a synchronized block on that same object.
• Misuse can lead to deadlocks or spurious wakeups, so consider using java.util.concurrent classes (e.g., Lock, Condition, BlockingQueue) in production code.
Thank you!