gpt4 book ai didi

java - CompletableFuture 如何知道任务是独立的?

转载 作者:行者123 更新时间:2023-11-30 08:43:44 24 4
gpt4 key购买 nike

假设我们有以下虚拟代码:

CompletableFuture<BigInteger> cf1 = CompletableFuture.supplyAsync(() -> BigInteger.valueOf(2L));
CompletableFuture<BigInteger> cf2 = CompletableFuture.supplyAsync(() -> BigInteger.valueOf(3L));
cf1.thenCombine(cf2, (x, y) -> x.add(y)).thenAccept(System.out::println);

在这种情况下,JVM 是否知道 cf1cf2 携带独立的线程?如果线程相互依赖(例如,使用一个数据库连接),将会发生什么变化?

更一般的,CompletableFuture是如何同步线程的?

最佳答案

CompletableFuture 与任何线程都没有关系。它只是一个结果的持有者,该结果与操作该结果的方法异步检索。

静态 supplyAsyncrunAsync 方法只是辅助方法。 supplyAsync 状态的 javadoc

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() with the value obtained by calling the given Supplier.

这或多或少等同于

Supplier<R> sup = ...;
CompletableFuture<R> future = new CompletableFuture<R>();
ForkJoinPool.commonPool().submit(() -> {
try {
R result = sup.get();
future.complete(result);
} catch (Throwable e) {
future.completeExceptionally(e);
}
});
return future;

CompletableFuture 被返回,甚至允许您在任务提交到池之前完成它。

More general, how does CompletableFuture synchronize threads?

它不会,因为它不知道哪些线程正在对其进行操作。 javadoc 中进一步暗示了这一点

Since (unlike FutureTask) this class has no direct control over the computation that causes it to be completed, cancellation is treated as just another form of exceptional completion. Method cancel has the same effect as completeExceptionally(new CancellationException()). Method isCompletedExceptionally() can be used to determine if a CompletableFuture completed in any exceptional fashion.

CompletableFuture 对象不控制处理。

关于java - CompletableFuture 如何知道任务是独立的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091401/

24 4 0