java - CompletableFuture, thenCompose 方法

标签 java multithreading java-8 threadpool completable-future

我对the contract有些误解的 thenCompose(Function<? super T,? extends CompletionStage<U>> fn) .这是那里所说的:

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage as the argument to the supplied function.

函数似乎接受了 CompletionStage 的结果, 而不是 CompletionStage本身。那么他们的意思是什么?

那么返回的 CompletableFuture 代表的任务呢? ?

Runnable r;
ExecutorService es;
Function<Void, CompletableFuture<Void>>f;
//...
CompletableFuture.runAsync(r, es)
.thenCompose(f);

是不是表示,一个任务,用CompletableFuture表示由 thenCompose 返回将在相同的 ThreadPool 中执行作为 Runnable r

最佳答案

这似乎是 JavaDoc 中的一个错误。其他方法如thenApply使用以下公式:

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function. […]

(重点是我自己)

此外,在 Java 9 中,formulation is now :

Returns a new CompletionStage that is completed with the same value as the CompletionStage returned by the given function.

When this stage completes normally, the given function is invoked with this stage's result as the argument, returning another CompletionStage. When that stage completes normally, the CompletionStage returned by this method is completed with the same value. […]

具体由哪个线程/线程池来执行这个函数,这个其实要看实现。

对于 CompletableFuture , 这在文档的顶部指出:

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.

在实践中,似乎有两种可能的情况:

  1. 如果这个阶段已经完成,那么函数会立即应用到调用thenCompose()的线程上;
  2. 如果这个阶段还没有完成,函数将应用到完成这个阶段的线程上(如果错误请指正)。

请注意,CompletableFuture 中没有“任务”。返回的 CompletableFuture 所做的唯一“任务”是将传递的函数返回的结果与其自身绑定(bind)。您负责执行将完成函数返回的 CompletableFuture 的任务。

关于java - CompletableFuture, thenCompose 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40175688/

相关文章:

java - Java 8 Streams 中的动态函数调用

java - 使用@ElementCollection hibernate 未保存的实例异常

iphone - 在 iOS 上管理 CPU 密集型线程

java - Java 8 中的谓词

java - 按钮单击调用不带参数的面板方法

c - Linux线程挂起/恢复

java - 使用套接字发送浮点值(从 Java 应用程序到 C#)

java - 类路径包含多个 SLF4J 绑定(bind),排除不起作用,

Java - 获取 JSON 对象数组?

C++多线程中断