Search code examples
javamultithreadingcompletable-futureforkjoinpool

How to set ForkJoinPool with the desired number of worker threads in CompletableFuture.supplyAsync(Supplier<U> supplier) method?


According to Oracle,

static CompletableFuture supplyAsync(Supplier supplier) Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() with the value obtained by calling the given Supplier.

static CompletableFuture supplyAsync(Supplier supplier, Executor executor) Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier.

If I use "static CompletableFuture supplyAsync(Supplier supplier)" method , it by default use ForkJoinPool.commonPool(). This returns a ForkJoinPool which has the number of worker threads equal to the number of available cores in the running machine.

But, I want to use a ForkJoinPool with my custom number of worker threads. Using the ForkJoinPool.commonPool() I cannot do that.

So how can I use CompletableFuture.supplyAsync method with my declared ForkJoinPool using the number of worker thread that I want?


Solution

  • ForkJoinPool implements Executor.

    Therefore, you can write your code like this:

    int threadCount = 3;
    ForkJoinPool myPool = new ForkJoinPool(threadCount);
    CompletableFuture cf = CompletableFuture.supplyAsync(mySup, myPool);