CompletableFuture的完成处理程序在哪个线程中执行? [英] In which thread does CompletableFuture's completion handlers execute in?

查看:732
本文介绍了CompletableFuture的完成处理程序在哪个线程中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对CompletableFuture方法有疑问:

I have a question about CompletableFuture method:

public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)

事情是JavaDoc说的只是这个:

The thing is the JavaDoc says just this:


返回一个新的CompletionStage,当这个阶段正常完成
时,执行此阶段的结果作为参数
提供的功能。有关特殊完成的规则​​
,请参阅CompletionStage文档。

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function. See the CompletionStage documentation for rules covering exceptional completion.

线程怎么样?这将在哪个线程中执行?如果未来由线程池完成怎么办?

What about threading? In which thread this is going to be executed? What if the future is completed by a thread pool?

推荐答案

CompletableFuture docs可以帮助您更好地理解:

The policies as specified in the CompletableFuture docs could help you understand better:



  • 为非异步方法的相关完成提供的操作可能是$ em $ b由完成当前CompletableFuture ,
    线程执行,或由完成方法的任何其他调用者执行。

使用 ForkJoinPool.commonPool()执行没有显式Executor参数的所有异步方法
(除非它不支持一个
并行度至少为2,在这种情况下,新的Thread是为运行每个任务创建的
。为了简化监视,调试和
跟踪,所有生成的异步任务都是标记
接口的实例 CompletableFuture.AsynchronousCompletionTask

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task). To simplify monitoring, debugging, and tracking, all generated asynchronous tasks are instances of the marker interface CompletableFuture.AsynchronousCompletionTask.

更新 :我也会建议阅读@Mike的这个答案,作为对文档细节的进一步有趣分析。

Update: I would also advice on reading this answer by @Mike as an interesting analysis further into the details of the documentation.

这篇关于CompletableFuture的完成处理程序在哪个线程中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆