ForkJoinPool executes task two times

Viewed 106

The following code prints out 'Inside...' two times.

import java.util.concurrent.ForkJoinPool;

public class Test {

  public static void main(String[] args) {

    ForkJoinPool forkJoinPool = new ForkJoinPool(3);

    forkJoinPool.submit(() -> {
      System.out.println("Inside...");
    }).invoke();
  }
}

Why is that?

1 Answers

You should not call both submit and invoke. ForkJoinPool#submit publishes the task to the pool, and will also execute it once a thread is ready.

The method also returns ForkJoinTask, on which you call invoke, performing the task again and waiting for its result.

Related