Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 940
Md. Habibullah Bin Ismail Avatar asked Apr 12 '16 09:04

Md. Habibullah Bin Ismail


1 Answers

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);
like image 193
flo Avatar answered Oct 13 '22 02:10

flo