Java Concurrency - (Object) Wait

About

Process / Thread - Waiting state in Java.

Object.wait, wait(long timeout) and wait(long timeout, int nanos) suspend the current thread.

The invocation of wait does not return until another thread has issued a notification that some special event may have occurred — though not necessarily the event this thread is waiting for.

When wait is invoked, the thread releases the lock and suspends execution.

Set

Every object has a wait set of threads.

Syntax

guarded block syntax example

public synchronized void guardedJoy() {
    // This guard only loops once for each special event, which may not
    // be the event we're waiting for.
    while(!joy) {
        try {
            wait();
        } catch (InterruptedException e) {}
    }
    System.out.println("Joy and efficiency have been achieved!");
}

Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.

Notification

  • Object.notifyAll, informing all threads waiting on that lock that something important has happened.
  • Object.notify wakes up arbitrary a single thread. Because notify doesn't allow you to specify the thread that is woken up, it is useful only in massively parallel applications — that is, programs with a large number of threads, all doing similar chores. In such an application, you don't care which thread gets woken up.

Documentation / Reference


Powered by ComboStrap