Java Concurrency - (Object) Wait

> Procedural Languages > Java > Java - Concurrency (Parallel Work)

1 - About

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.

Advertising

3 - Set

Every object has a wait set of threads.

4 - 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.

5 - 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.

6 - Documentation / Reference