【问题标题】:Java CompletableFuture assigning executorJava CompletableFuture 分配执行器
【发布时间】:2019-02-07 22:03:56
【问题描述】:

我对在 CompletableFuture 中定义执行者感到困惑。我不确定如何告诉 CompletableFuture 在该特定执行程序中运行它。提前致谢。

//Suppose I have an executor
ExecutorService myExecutor=Executors.newFixedThreadPool(2);

//If I create a future like this
CompletableFuture.runAsync(() -> {
      //Do something
}, myExecutor); // I can put the executor here and say the future to this executor

//But I do not know where to put executor if I create my future in method style like this

private final CompletableFuture<Void> myMethod(String something) {
  //Do something
    return null;
}

//and use it like this  
.thenCompose(this::myMethod); //How can I specify the executor in this case?

【问题讨论】:

  • 你是在问如何在执行器中运行myMethod,就像使用thenComposeAsync​而不是thenCompose一样简单,或者你是在问如何控制@内发生的事情987654325@关于返回的未来,这是不可能的?

标签: java asynchronous executorservice completable-future concurrent.futures


【解决方案1】:

在您的示例中,您有 3 个 CompletableFutures 在起作用:

  1. runAsync()返回的那个
  2. myMethod()返回的那个
  3. thenCompose()返回的那个

您还有 4 个任务需要运行:

  1. 传递给runAsync() 的那个将在给定的执行器上执行并处理未来1;
  2. thenCompose()调用myMethod()来创建future 2的那个可以在任何executor上运行,使用thenComposeAsync()明确选择一个;
  3. 将完成由myMethod() 返回的future 2 - 这将在myMethod() 自身内部进行控制;
  4. 将完成由 thenCompose() 返回的未来 3 的那个——这是在内部处理的,取决于执行顺序(例如,如果 myMethod() 返回一个已经完成的未来,它也会完成前者)。

如您所见,涉及多个任务和执行器,但您始终可以使用*Async() 变体控制在独立阶段中使用的执行器。您无法真正控制它的唯一情况是第 4 种情况,但只要相关阶段也使用 *Async() 变体,这是一种廉价的操作。

【讨论】:

    【解决方案2】:

    你可以这样做:

    ExecutorService es = Executors.newFixedThreadPool(4);
    List<Runnable> tasks = getTasks();
    CompletableFuture<?>[] futures = tasks.stream()
                                   .map(task -> CompletableFuture.runAsync(task, es))
                                   .toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(futures).join();    
    es.shutdown();
    

    【讨论】:

    • 这很有趣。这是唯一的方法吗? OP 似乎试图先制作一种复合类型的CompletableFuture,然后再提交。而您首先创建个人CompletableFutures,然后将它们组合成一个更大的“虚拟”未来对象。 OP的方式可行吗? (当我查看 API 时似乎不是。)
    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多