Java CompletableFuture分配执行程序

问题描述 投票:1回答:2

我对在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?
java asynchronous executorservice completable-future concurrent.futures
2个回答
1
投票

你可以这样做:

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();

0
投票

在你的例子中,你有3个CompletableFutures在玩:

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

您还需要运行4个任务:

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

如您所见,涉及多个任务和执行程序,但您始终可以使用*Async()变体控制在依赖阶段中使用的执行程序。唯一没有真正控制它的情况是第四种情况,但只要依赖阶段使用*Async()变体,它也是一种廉价的操作。

© www.soinside.com 2019 - 2024. All rights reserved.