J2EEOnline J2EE






Threading Model   «Prev  Next»
Lesson 8Waiting and notifying
ObjectiveDescribe how the wait() and notify() methods are used to synchronize access to shared resources.

Waiting and Notifying Threads using the Consumer Producer Model

Advanced synchronization: waiting and notifying


wait-notify
More advanced synchronization can be accomplished using the
  1. wait(),
  2. notify(), and
  3. notifyAll() methods of the
Object class. You can use these methods to cause threads to wait until an object is updated by another thread.
As an example, consider the situation where an object supports Consumer and Producer threads. Consumer threads consume information provided by the object.
Producer threads produce information that is provided to the object. Consumers wait until Producers update the object's information before consuming that information.

Using wait() and notify() to support consumers and producers.
Using wait() and notify() to support consumers and producers.

The
  1. wait(),
  2. notify(), and
  3. notifyAll()
methods are used by Consumers and Producers as follows:

  1. A Consumer thread invokes a synchronized method of an object and acquires the object's lock. The synchronized method tests to see if the object has been updated. If not, the object's wait() method is invoked. This causes the thread to lose the object's lock and wait until the object has been updated.
  2. A Producer thread updates the object and invokes the object's notify() or notifyAll() methods. The notify() method causes a waiting Consumer thread to be returned to the ready state.
    The notifyAll() method causes "all of the Consumer threads" to be returned to the ready state.
  3. When a waiting Consumer thread reenters the running state, it reacquires the lock on the object and can then continue its processing and consume the object's resources .

An object typically implements the wait(), notify(), and notifyAll() methods using synchronized methods of the following form:

class MyObject {
  boolean available;
  public synchronized ReturnType consumeIt(parameterList) {
    while (!available) {
      wait();
    }
    // Return information to the Consumer.
  }
  public synchronized void produceIt(parameterList) {
    // Update the object.
    available = true;
    notifyAll();
  }
}