简体   繁体   English

CompletableFuture 与 java 中的 ExecutorService

[英]CompletableFuture with ExecutorService in java

I am trying to implement a thread pool using ExecutorService and CompletableFuture in java.我正在尝试在 java 中使用 ExecutorService 和 CompletableFuture 实现线程池。 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.如果我没有在可完成的未来任务中通过此处的执行程序服务,它将在我阅读时在内部使用 Fork/Join 公共池。 Now my question is should I pass executor service here externally or not and let it use Fork/Join common pool internally?现在我的问题是我是否应该在外部通过执行器服务并让它在内部使用 Fork/Join 公共池? 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?您打算使用 CompletableFuture 运行哪些类型的任务? How many CPUs does your machine have?你的机器有多少个 CPU?

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 .它是ForkJoinPool.ManagedBlocker You may check the official documentation if you want to do some digging and experiments.如果你想做一些挖掘和实验,你可以查看官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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