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

How does CompletableFuture know that tasks are independent?

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

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 (CF) "synchronizes threads"。如果您没有提供执行程序,它会使用执行程序 you have provided or the common pool

当您调用 supplyAsync 时,CF 将各种任务提交到该池,该池又管理底层线程以执行任务。

它不知道,也不会尝试同步任何内容。正确同步对可变共享数据的访问仍然是客户端的责任。

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

static 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 对象不控制处理。