简体   繁体   中英

CompletableFuture with ExecutorService in java

I am trying to implement a thread pool using ExecutorService and CompletableFuture in java. Here I have passed the fixed-size pool to completable future tasks. if I don't pass the executor service here in completable future tasks it will use Fork/Join common pool internally as I read. Now my question is should I pass executor service here externally or not and let it use Fork/Join common pool internally? which is better in which case?

    ExecutorService es = Executors.newFixedThreadPool(4);
    List<CompletableFuture<?>> futures = new ArrayList<>();
    for(item i: item[]){
       CompletableFuture<Void> future = CompletableFuture.runAsync(() -> MyClass.service(i), es);
       futures.add(future);
    }
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();

It's not possible to give a fully accurate answer to your question without knowing the specifics. Which kinds of tasks do you intend to run using CompletableFuture? How many CPUs does your machine have?

In general, I would suggest avoiding using the common pool, since it may bring you some unexpected bugs up to blocking all parts of your application that rely on using the common pool.

Talking more specifically, you need to understand which type of tasks will you be running: blocking or non-blocking? Blocking tasks are those ones that use any external dependencies like database invocation and communication with other services/applications, synchronization, thread sleeps, or any other blocking utilities.

The best approach will be the creation of a separate thread pool for blocking tasks that you can fully manage. This will allow you to isolate other parts of your application and have stable and predictable execution and performance behavior for all your non-blockings tasks.

However, there is one a bit advanced workaround that may allow you to use the common pool even for blocking tasks. It's ForkJoinPool.ManagedBlocker . You may check the official documentation if you want to do some digging and experiments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM