Java - Thread Phasers

What is Phaser?

Phaser is another kind of synchronization barrier.

It provides the following functions:

Item
Meaning
Reuse
Phaser is reusable.
Number of subtasks




The number of parties to synchronize on a Phaser can change dynamically.
A Phaser has three types of parties count:
a registered parties count,
an arrived parties count,
and an unarrived parties count.
A Phase number



A phase number starts at zero.
When all registered parties arrive, Phaser moves to the next phase and phase number is incremented by one.
The maximum value of the phase number is Integer.MAX_VALUE.
After its maximum value, the phase number restarts at zero.
Termination state

A Phaser has a termination state.
All synchronization methods called on a Phaser in a termination state return immediately without waiting for an advance.
Phaser action

phaser action is the action to combine the result of subtasks.
To add phaser action, subclass Phaser class and override the onAdvance() method to provide a Phaser action.

API

Phaser class from java.util.concurrent package is an implementation of phaser.

You can create a Phaser with no initially registered party using its default constructor.

Phaser phaser = new Phaser(); // A phaser with no registered parties

To register parties when the Phaser is created.

Phaser phaser = new Phaser(5); // A phaser with 5 registered parties

You can create a tree structure like Phaser by specifying the parent of the newly created Phaser.

Subtask

You can register a subtask with a Phaser in the following ways:

You can deregister a registered party using the arriveAndDeregister().

The following Class Represents Tasks That Start Together by Synchronizing on a Phaser

Demo

import java.util.Random;
import java.util.concurrent.Phaser;

class MyTask extends Thread {
  private Phaser phaser;
  private String taskName;
  public MyTask(String taskName, Phaser phaser) {
    this.taskName = taskName;
    this.phaser = phaser;
  }/*from   w ww  . j  a  v a 2s. c o  m*/

  @Override
  public void run() {
    System.out.println(taskName + ":Initializing...");

    int sleepTime = 3;
    try {
      Thread.sleep(sleepTime * 1000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println(taskName + ":Initialized...");
    // Wait for all parties to arrive to start the task
    phaser.arriveAndAwaitAdvance();
    System.out.println(taskName + ":Started...");
  }
}

public class Main {
  public static void main(String[] args) {
    // Start with 1 registered party
    Phaser phaser = new Phaser(1);
    // Let's start three tasks
    final int TASK_COUNT = 3;
    for (int i = 1; i <= TASK_COUNT; i++) {
      phaser.register();
      String taskName = "Task #" + i;
      MyTask task = new MyTask(taskName, phaser);
      task.start();
    }
    // Now, deregister the self, so all tasks can advance
    phaser.arriveAndDeregister();
  }
}

Result

Related Topics