Concurrency - Guarded block (Thread Communication Idiom)

> (Data|State) Management and Processing > (Concurrency|Parallel|Asynchronous) programming

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

Advertising

3 - Java Example

3.1 - Don't do this

The loop is wasteful, since it executes continuously while waiting.

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

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

4 - Documentation / Reference

Advertising
data/concurrency/guarded_block.txt · Last modified: 2018/09/22 16:47 by gerardnico