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

标签 java concurrency java-8 java.util.concurrent completable-future

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

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 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/

相关文章:

java - Java中的并发(FX)

multithreading - 什么是竞争条件?

swift - 数组默认按值传递&线程安全

java - 使用 java Streams 转换嵌套列表

如果只有一个值,Java 8 收集器会返回一个值

java - 使用 StreamSupport 库时 Dex 失败

java - 构建健康指标 spring boot

java - .docx 正在从 Sun One Web 服务器下载为 IE 上的 .zip 文件

java - 使用 Log4j 进行日志记录

java - 使用Java将Microsoft Office文档和PDF文档转换为图像文件