Wait() and Notify()

This lesson explains the wait and notify methods exposed by every object.

We'll cover the following...

Question # 1

Explain the wait() method.

The wait() method is exposed on each jJava object. Each Java object can act as a condition variable. When a thread executes the wait() method, it releases the monitor for the object and is placed in the wait queue. Note that the thread must be inside a synchronized block of code that synchronizes on the same object as the one on which wait() is being called, or in other words, the thread must hold the monitor of the object on which it'll call wait(). If not so, an illegalMonitor exception is raised. Following is the general idiom for using wait().

General Idiom to use wait

   // The standard idiom for using the wait() method
   synchronized (obj) {
       while (<condition does not hold>)
           obj.wait(); // Lock released & reacquired on wakeup
           // ...         Do Processing
   }

Question # 2

Why is it necessary to wrap the wait() method call in a while loop? ...