假设我们有以下虚拟代码:
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 是否知道 cf1 和 cf2 承载独立线程?如果线程相互依赖(例如,使用一个数据库连接),将会发生什么变化?
更一般地说,CompletableFuture
如何同步线程?
最佳答案
CompletableFuture
与任何线程都没有关系。它只是异步检索结果的持有者,并使用对该结果进行操作的方法。
静态
supplyAsync
和 runAsync 方法只是辅助方法。 supplyAsync
的 javadoc 状态
Returns a new
CompletableFuture
that is asynchronously completed by a task running in theForkJoinPool.commonPool()
with the value obtained by calling the givenSupplier
.
这或多或少相当于
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 ascompleteExceptionally(new CancellationException())
. MethodisCompletedExceptionally()
can be used to determine if aCompletableFuture
completed in any exceptional fashion.
CompletableFuture
对象不控制处理。
关于java - CompletableFuture 如何知道任务是独立的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091401/