How can the wait() and notify() methods be called on Objects that are not threads?

Alexander Mills picture Alexander Mills · Apr 24, 2013 · Viewed 54.8k times · Source

How can the wait() and notify() methods be called on Objects that are not Threads? That doesn't really make sense, does it?

Surely, it must make sense, however, because the two methods are available for all Java objects. Can someone provide an explanation? I am having trouble understanding how to communicate between threads using wait() and notify().

Answer

Nathan Hughes picture Nathan Hughes · Apr 24, 2013

Locking is about protecting shared data.

The lock is on the data structure being protected. The threads are the things accessing the data structure. The locks are on the data structure object in order to keep the threads from accessing the data structure in an unsafe way.

Any object can be used as an intrinsic lock (meaning used in conjunction with synchronized). This way you can guard access to any object by adding the synchronized modifier to the methods that access the shared data.

The wait and notify methods are called on objects that are being used as locks. The lock is a shared communication point:

  • When a thread that has a lock calls notifyAll on it, the other threads waiting on that same lock get notified. When a thread that has a lock calls notify on it, one of the threads waiting on that same lock gets notified.

  • When a thread that has a lock calls wait on it, the thread releases the lock and goes dormant until either a) it receives a notification, or b) it just wakes up arbitrarily (the "spurious wakeup"); the waiting thread remains stuck in the call to wait until it wakes up due to one of these 2 reasons, then the thread has to re-acquire the lock before it can exit the wait method.

See the Oracle tutorial on guarded blocks, the Drop class is the shared data structure, threads using the Producer and Consumer runnables are accessing it. Locking on the Drop object controls how the threads access the Drop object's data.

Threads get used as locks in the JVM implementation, application developers are advised to avoid using threads as locks. For instance, the documentation for Thread.join says:

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Java 5 introduced explicit locks implementing java.util.concurrent.locks.Lock. These are more flexible than the implicit locks; there are methods analogous to wait and notify (await and signal), but they are on the Condition, not on the lock. Having multiple conditions makes it possible to target only those threads waiting for a particular type of notification.