Explain wait(), notify(), and notifyAll() in Java

๐Ÿ’ก Concept: Inter-thread Communication

The methods wait(), notify(), and notifyAll() in Java are used for inter-thread communication, allowing threads to wait and notify each other using object monitors.

๐Ÿ“˜ Quick Intro

These methods are defined in the Object class and must be called inside synchronized blocks or methods. They help manage cooperation between threads rather than competition.

๐Ÿง  Analogy

Imagine workers at a loading dock. One waits for a shipment (wait), another signals when the shipment has arrived (notify), or informs all waiting workers at once (notifyAll).

๐Ÿ”ง Technical Explanation

  • wait(): Releases the lock and causes the current thread to wait until another thread calls notify() or notifyAll().
  • notify(): Wakes up one randomly selected thread waiting on the object's monitor.
  • notifyAll(): Wakes up all threads waiting on the object's monitor.
  • All three methods must be used within synchronized context, or an IllegalMonitorStateException is thrown.

๐ŸŽฏ Use Cases

  • โœ… Implementing producer-consumer problems.
  • โœ… Coordinating resource sharing among threads.
  • โœ… Avoiding busy-wait loops by blocking until notified.

๐Ÿ’ป Example: wait() and notify()


class SharedResource {
    private boolean available = false;

    public synchronized void produce() {
        available = true;
        System.out.println("Produced item");
        notify();
    }

    public synchronized void consume() {
        while (!available) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        System.out.println("Consumed item");
        available = false;
    }
}

public class WaitNotifyExample {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        new Thread(resource::consume).start();
        new Thread(resource::produce).start();
    }
}

โ“ Interview Q&A

Q1: What is the purpose of wait()?
A: To pause the current thread until it is notified.

Q2: Where can wait() be used?
A: Inside synchronized blocks or methods only.

Q3: What happens if wait() is called outside synchronization?
A: It throws IllegalMonitorStateException.

Q4: Difference between notify() and notifyAll()?
A: notify() wakes up one thread; notifyAll() wakes up all waiting threads.

Q5: Do these methods belong to Thread class?
A: No, they belong to Object class.

Q6: Can wait() be interrupted?
A: Yes, it throws InterruptedException if interrupted.

Q7: Is notify() deterministic?
A: No, the selected thread is not guaranteed.

Q8: Can you use notify() without wait()?
A: It's possible but meaningless if no thread is waiting.

Q9: How do these methods help efficiency?
A: They avoid CPU wastage by preventing busy-waiting.

Q10: Can these methods be used with static synchronization?
A: Yes, with proper locking on the Class object.

๐Ÿ“ MCQs

Q1. What does wait() do in Java?

  • Terminates thread
  • Causes the current thread to wait and release the lock
  • Locks the object
  • Executes immediately

Q2. Which class defines wait() and notify()?

  • Thread
  • Runnable
  • Object
  • Monitor

Q3. What happens if notify() is used without synchronized?

  • Nothing
  • IllegalMonitorStateException
  • Thread dies
  • Deadlock

Q4. What is the key difference between notify() and notifyAll()?

  • No difference
  • notify() wakes one thread, notifyAll() wakes all
  • notifyAll() is deprecated
  • notify() is faster

Q5. Can wait() throw exceptions?

  • No
  • Yes, InterruptedException
  • Only in debug mode
  • Only for IO threads

Q6. Which keyword must be used with wait()?

  • static
  • volatile
  • synchronized
  • final

Q7. Which method wakes up one waiting thread?

  • notify()
  • wake()
  • signal()
  • resume()

Q8. Are wait(), notify() blocking methods?

  • No
  • Yes
  • Sometimes
  • Only if static

Q9. Do these methods help prevent busy-waiting?

  • No
  • Yes
  • Not always
  • They cause busy-wait

Q10. What happens if no thread is waiting during notify()?

  • Deadlock
  • Error
  • Nothing happens
  • All threads start

๐Ÿ’ก Bonus Insight

Use higher-level concurrency constructs like Condition, BlockingQueue, or CountDownLatch when possible for more readable and safer inter-thread communication.

๐Ÿ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

๐Ÿ” Navigation

Learn More About Java โ˜•

What is Java and its key features ๐Ÿ‘‰ Explained
Explain the Java Virtual Machine (JVM) ๐Ÿ‘‰ Explained
Difference between JDK, JRE, and JVM ๐Ÿ‘‰ Explained
What are Javaโ€™s main data types ๐Ÿ‘‰ Explained
Explain the concept of Object-Oriented Programming in Java ๐Ÿ‘‰ Explained
What is the difference between a class and an object ๐Ÿ‘‰ Explained
Explain encapsulation with an example ๐Ÿ‘‰ Explained
What is inheritance in Java and its types ๐Ÿ‘‰ Explained
Define polymorphism in Java with examples ๐Ÿ‘‰ Explained
What is abstraction in Java ๐Ÿ‘‰ Explained
Difference between abstract class and interface in Java ๐Ÿ‘‰ Explained
Explain method overloading and method overriding in Java ๐Ÿ‘‰ Explained
What are constructors in Java ๐Ÿ‘‰ Explained
What is the use of the static keyword in Java ๐Ÿ‘‰ Explained
Explain the difference between final, finally, and finalize in Java ๐Ÿ‘‰ Explained
Share:

Tags:


Feedback Modal Popup