Every object, in addition to having an associated lock, has an associated wait set, which is a set of threads. When an object is first created, its wait set is empty.
Wait sets are used by the methods wait
(§20.1.6, §20.1.7, §20.1.8), notify
(§20.1.9), and notifyAll
(§20.1.10) of class Object
. These methods also interact with the scheduling mechanism for threads (§20.20).
The method wait
should be called for an object only when the current thread (call it T) has already locked the object's lock. Suppose that thread T has in fact performed N lock actions that have not been matched by unlock actions. The wait
method then adds the current thread to the wait set for the object, disables the current thread for thread scheduling purposes, and performs N unlock actions to relinquish the lock. The thread T then lies dormant until one of three things happens:
notify
method for that object and thread T happens to be the one arbitrarily chosen as the one to notify.
notifyAll
method for that object.
The thread T is then removed from the wait set and re-enabled for thread scheduling. It then locks the object again (which may involve competing in the usual
manner with other threads); once it has gained control of the lock, it performs
additional lock actions and then returns from the invocation of the wait
method. Thus, on return from the wait
method, the state of the object's lock is
exactly as it was when the wait
method was invoked.
The notify
method should be called for an object only when the current thread has already locked the object's lock. If the wait set for the object is not empty, then some arbitrarily chosen thread is removed from the wait set and re-enabled for thread scheduling. (Of course, that thread will not be able to proceed until the current thread relinquishes the object's lock.)
The notifyAll
method should be called for an object only when the current thread has already locked the object's lock. Every thread in the wait set for the object is removed from the wait set and re-enabled for thread scheduling. (Of course, those threads will not be able to proceed until the current thread relinquishes the object's lock.)
These pearls of thought in Persian gulfs were bred,
Each softly lucent as a rounded moon;
The diver Omar plucked them from their bed,
Fitzgerald strung them on an English thread.
James Russell Lowell, in a copy of Omar Khayyam