gpt4 book ai didi

java - 编写 Java CompletableFutures 时使用哪个执行器?

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:05 25 4
gpt4 key购买 nike

我在某个存储库类上有一个方法,它返回一个 CompletableFuture。完成这些 futures 的代码使用了一个阻塞的第三方库。我打算有一个单独的有界 Executor,这个存储库类将使用它来进行这些阻塞调用。

这是一个例子:

public class PersonRepository {
private Executor executor = ...
public CompletableFuture<Void> create(Person person) {...}
public CompletableFuture<Boolean> delete(Person person) {...}
}

我的应用程序的其余部分将组成这些 future 并对结果做一些其他事情。当提供给 thenAcceptthenComposewhenComplete 等的这些其他函数时,我不希望它们在 上运行存储库的执行者

另一个例子:

public CompletableFuture<?> replacePerson(Person person) {
final PersonRepository repo = getPersonRepository();
return repo.delete(person)
.thenAccept(existed -> {
if (existed) System.out.println("Person deleted"));
else System.out.println("Person did not exist"));
})
.thenCompose(unused -> {
System.out.println("Creating person");
return repo.create(person);
})
.whenComplete((unused, ex) -> {
if (ex != null) System.out.println("Creating person");
repo.close();
});
}

JavaDoc 声明:

Actions supplied for dependent completions of non-async methods may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method.

附带问题:为什么这里有一个?在什么情况下存在未完成当前 future 的完成方法的另一个调用者?

主要问题:如果我希望所有的 println 都由不同于存储库使用的 Executor 执行,哪些方法我需要异步并手动提供执行程序吗?

很明显,thenAccept 需要更改为 thenAcceptAsync,但我不确定这一点。

替代问题:哪个线程完成从 thenCompose 返回的 future?

我的猜测是,它将是完成从函数参数返回的 future 的任何线程。换句话说,我还需要将 whenComplete 更改为 whenCompleteAsync

也许我把事情复杂化了,但这感觉可能会变得非常棘手。我需要非常注意所有这些 future 的来源。同样从设计的角度来看,如果我返回一个 future ,我如何防止调用者使用我的执行者?感觉就像它打破了封装。我知道 Scala 中的所有转换函数都采用隐式 ExecutionContext,这似乎可以解决所有这些问题。

最佳答案

附带问题:如果您将中间 CompletionStage 分配给一个变量并在其上调用一个方法,它将在同一线程上执行。

主要问题:只有第一个,所以将 thenAccept 更改为 thenAcceptAsync -- 以下所有问题都将在用于接受的线程上执行它们的步骤。

备选问题:从 thenCompose 完成 future 的线程与用于撰写的线程相同。

您应该将 CompletionStages 视为在同一线程上快速连续执行的步骤(通过按顺序应用函数),除非您特别希望使用异步在不同的线程上执行该步骤。然后所有后续步骤都在该新线程上完成。

在您当前的设置中,这些步骤将像这样执行:

Thread-1: delete, accept, compose, complete

有了第一个 accept async,它就变成了:

Thread-1: delete
Thread-2: accept, compose, complete

关于你的最后一个问题,关于你的调用者使用的同一个线程,如果他们添加了额外的步骤——我认为除了不返回 CompletableFuture 之外你无能为力,而是一个普通的 Future

关于java - 编写 Java CompletableFutures 时使用哪个执行器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42705950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com