我对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.
在实践中,似乎有两种可能的情况:
- 如果这个阶段已经完成,那么函数会立即应用到调用
thenCompose()
的线程上; - 如果这个阶段还没有完成,函数将应用到完成这个阶段的线程上(如果错误请指正)。
请注意,CompletableFuture
中没有“任务”。返回的 CompletableFuture
所做的唯一“任务”是将传递的函数返回的结果与其自身绑定(bind)。您负责执行将完成函数返回的 CompletableFuture
的任务。
关于java - CompletableFuture, thenCompose 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40175688/