Search code examples
javaexecutorservicejava-threadsforkjoinpool

ForkJoinPool executes task two times


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?


Solution

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