Java Thread How to - Wait until all tasks have finished in ForkJoinPool








Question

We would like to know how to wait until all tasks have finished in ForkJoinPool.

Answer

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicLong;
/*  w w  w.ja va 2 s  .co m*/
public class Main {
  static ForkJoinPool executors;
  public static void main(String[] args) throws InterruptedException {
    executors = new ForkJoinPool();
    List<Long> sequence = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
      sequence.add(fib(i));
    }
    System.out.println(sequence);
  }
  private static Long fib(int n) throws InterruptedException {
    AtomicLong result = new AtomicLong();
    Phaser phaser = new Phaser();
    Task initialTask = new Task(n, result, phaser);
    phaser.register();
    executors.submit(initialTask);
    phaser.arriveAndAwaitAdvance();
    return result.get();
  }
}
class Task implements Runnable {
  int index;
  AtomicLong result;
  Phaser phaser;
  public Task(int n, AtomicLong result, Phaser phaser) {
    index = n;
    this.result = result;
    this.phaser = phaser;
    phaser.register();
  }
  @Override
  public void run() {
    if (index == 1) {
      result.incrementAndGet();
    } else if (index > 1) {
      Task task1 = new Task(index - 1, result, phaser);
      Task task2 = new Task(index - 2, result, phaser);
      Main.executors.submit(task1);
      Main.executors.submit(task2);
    }
    phaser.arrive();
  }
}