Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The Object.wait() method is used to temporarily cede possession of a lock so that another requesting thread can proceed. It must always be used inside a synchronized block or method. To let the waiting thread resume, the requesting thread must notify it. Furthermore, the wait() method should be invoked in a loop that checks if a condition predicate holds. Note that a condition predicate is not the same as the condition expression in the loop. For example, the condition predicate for removing an element from a vector is !isEmpty() whereas the condition expression for the while loop condition is isEmpty(). The correct way to invoke wait() when the vector is empty is shown below.

Code Block
synchronizedpublic void consumeElement(object) {
  whilesynchronized (<condition does not hold>vector) {
    while (vector.isEmpty()) {
      object.wait(); 
    }

    // ProceedConsume when condition holds
  }
}

The notification mechanism notifies the waiting thread and lets it check its condition predicate. The invocation of notify() or notifyAll() in another thread cannot precisely determine which waiting thread must be resumed. A condition predicate statement is used so that the correct thread resumes when it receives a notification. A condition predicate also helps when a thread is required to block until a condition becomes true, for instance, when it should not proceed without reading some data from an input stream.

...