About

The most common coordination idiom between thread is the guarded block.

Such a block begins by polling a condition that must be true before the block can proceed.

Java Example

Don't do this

The loop is wasteful, since it executes continuously while joy is false.

public void guardedJoy() {
    // Simple loop guard. Wastes
    // processor time. Don't do this!
    while(!joy) {}
    System.out.println("Joy has been achieved!");
}

Do this

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!");
}

The invocation of wait does not return until another thread has issued a notification that some special event may have occurred. See Java Concurrency - (Object) Wait

Example of notification:

public synchronized notifyJoy() {
    joy = true;
    Object.notifyAll();
}

where: notifyAll

Invoke wait inside:

  • a synchronized method. It is a simple way to acquire the intrinsic lock because (Suppose d is the object we're using to invoke wait) When a thread invokes d.wait, it must own the intrinsic lock for d.
  • 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.

Documentation / Reference