Table of Contents

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

Documentation / Reference