Table of Contents

Concurrency - Guarded block (Thread Communication Idiom)

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:

Documentation / Reference