Waiting – Concurrency: Part I

Waiting

Coordination between threads is facilitated by waiting and notifying, as illustrated by Figures 22.9 and 22.10. A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met. The thread leaves the RUNNING substate and transits to the WAITING or TIMED_WAITING state, depending on whether a timeout was specified in the call. The thread releases ownership of the object lock.

Figure 22.9 Timed Waiting and Notifying

Transitioning to a waiting state and releasing the object lock are completed as one atomic (non-interruptible) operation. The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object, after acquiring its lock.

Note that the waiting thread releases only the lock of the object on which the wait() method was invoked. It does not release any other object locks that it might hold, which will remain locked while the thread is waiting.

Each object has a wait set containing threads waiting for notification. Threads in a waiting state are grouped according to the object whose wait() method they invoked.

Figure 22.10 shows a thread t1 that first acquires a lock on the shared object, and afterward invokes the wait() method on the shared object. This releases the object lock, the thread t1 is added to the wait set of the object, and the thread waits to be notified in the WAITING state. While the thread t1 is waiting, another thread t2 can acquire the lock on the shared object for its own purpose.

Depending on whether a timeout was specified or not in the call to the wait() method, a call to the getState() method on thread t1 while it is in a waiting state will return the value Thread.State.TIMED_WAITING or Thread.State.WAITING, respectively.

A thread in a waiting state can be awakened by the occurrence of any one of these events:

  • Another thread invokes the notify() method on the object of the waiting thread, and the waiting thread is selected as the thread to be awakened.
  • The waiting thread times out if it was a timed wait.
  • Another thread interrupts the waiting thread.
  • A spurious wakeup occurs.

Figure 22.10 Thread Coordination

Leave a Reply

Your email address will not be published. Required fields are marked *