DEV Community

Cover image for Wait for completion of all tasks with Java Phaser
Franz Wong
Franz Wong

Posted on

Wait for completion of all tasks with Java Phaser

Problem

Producer wants to wait for completion of all tasks before proceeding.

Solution

Producer side

// Add producer as a party
Phaser phaser = new Phaser(1);

for (int i=0; i<10000; ++i) {
  // Add each task as a party
  phaser.register();
  queue.put(new Task());
}

// Producer arrived and wait for completion of all tasks
phaser.arriveAndAwaitAdvance();

// At the end, there is only 1 party left which is the producer itself
Enter fullscreen mode Exit fullscreen mode

Consumer side

while (true) {
  Task task = queue.take();
  processTask(task);
  // Task completed and remove itself as a party
  phaser.arriveAndDeregister();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)