当前位置:网站首页>Gauva的ListenableFuture
Gauva的ListenableFuture
2022-08-03 08:08:00 【鲲鹏飞九万里】
Guava的ListenableFuture
一、ListenableFuture 介绍
并发是一个困难问题,但是通过强大和强大的抽象能够显著的简化工作。为了简化问题,Gauva使用ListenableFuture扩展了JDK的Future接口,
**我们强烈建议你在你所有的代码中使用ListenableFuture
代替Future
,**因为:
- 大多数的
Future
方法需要它; - 这比以后更改为
ListenableFuture
更容易; - 实用方法的提供者不需要提供
Future
和ListenableFuture
方法的变体;
二、接口
传统的Future
代表着异步计算的结果:一个计算可能也可能没有完成生成结果。Future可以是一个程序计算的句柄,一个来自服务的承诺提供给我们一个结果。
ListenableFuture
允许你注册一个回调函数,一旦计算是完成或者计算是已经完成,回调函数会立马执行。这个简单的添加能有效的支持多种Future接口不支持的操作。
基础的操作被ListenableFuture
添加是通过addListener(Runnable, Executor)
,它指定了当Future
的计算完成之后,指定的Runnable
将会在Executor
中执行。
三、添加回调函数
大多数用户更喜欢使用Futures.addCallback(ListenableFuture, FutureCallback, Executor)
,一个FutueCallback
有两个方法:
onSuccess(V)
如果future执行成功,基于结果进行执行。onFailure(Throwable)
如果future执行失败,基于失败进行执行。
四、创建
相对于JDKExecutorService.submit(Callable)
方法初始化一个异步的计算。Guava提供了一个ListeningExecutorService
接口,它能在任何ExecutorService
返回一个正常Future
的地方,返回一个ListenableFuture
。为了将ExecutorService
转换成ListeningExecutorService
,仅需要使用MoreExecutors.listeningDecorator(executorService)
:
ListeningExecutorService service =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()));
ListenableFuture<String> listenableFuture = service.submit(() -> callDemo());
Futures.addCallback(listenableFuture, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
System.out.println("Run Ok : " + result);
// service.shutdown();
}
@Override
public void onFailure(Throwable t) {
System.out.println("Run Fail: " + t);
}
}, service);
或者,如果你从一个基于FutureTask
的API进行转换,Guava提供了ListenableFutureTask.create(Callable)
和ListenableFutureTask.create(Runnable, V)
。并不像JDK,ListenableFutureTask
并不意味着直接扩展。
如果您更喜欢设置未来值的抽象而不是实现计算值的方法,请考虑扩展 AbstractFuture<V>
或直接使用 SettableFuture
。
如果你必须将另一个API提供的Future转换成ListenableFuture
,你没有选择除了使用重量级的JdkFutureAdapters.listenInPoolThread(Future)
,将Future转化成ListenableFuture
。无论什么时候,只要有可能,都应该修改源代码去返回一个ListenableFuture
。
五、应用
使用ListenableFuture
的重要原因是,它让异步的链操作成为可能。
很多有效的其它操作使用ListenableFuture
是支持的,而单独使用Future
是不支持的。不同的操作能够被不同的Executor执行,并且单个 ListenableFuture 可以有多个等待它的操作。
当多个操作应该在另一个操作开始时立即开始时——“扇出”——ListenableFuture 才起作用:它触发所有请求的回调。通过稍微多一点的工作,我们能“扇入”,或触发ListenableFuture
进行计算只要若干个其它的Future执行完(看:Futures.allAsList
)。
方法 | 描述 | 延伸 |
---|---|---|
Futures.transformAsync(ListenableFuture, AsyncFunction, Executor) | 返回一个新的ListenableFuture ,它的结果是应用AsyncFunction。AsyncFunction是对ListenableFuture结果的加工 | |
Futures.transform(ListenableFuture, Function, Executor) | 返回一个新的ListenableFuture ,它的结果是应用Function。Function是对ListenableFuture结果的加工 | |
Futures.allAsList(Iterable<ListenableFuture<V>>) | 返回一个ListenableFuture ,它的值是一个list包含了每一个输入输入future的值。如果任何的future失败或取消,这个future也失败或取消。 | |
Futures.successfulAsList(Iterable<ListenableFuture>) | 返回一个ListenableFuture ,它的值是一个list包含了每一个输入输入future的值。如果相对应的future失败或取消,将用null代替。 |
一个AsyncFunction
提供了一个方法ListenableFuture<B> apply(A a)
。它用于异步传输一个值。
六、避免内嵌的Future
ListenableFuture<ListenableFuture<String>> nestedFuture =
executorService.submit(() -> otherExecutorService.submit(() -> callDemo()));
上面的代码是不正确的, 因为如果外部Future的取消与外部Future的完成竞争,则该取消不会传播到内部Future。 使用 get() 或侦听器检查其他Future的失败也是一个常见错误,但除非特别注意,否则从 otherCallable 抛出的异常将被抑制。
为了避免这种情况,Guava 的所有Future处理方法(以及一些来自 JDK)都有 *Async 版本,可以安全地解开这个嵌套:
Futures.transformAsync(ListenableFuture, AsyncFunction, Executor)
ExecutorService.submit(Callable)
Futures.submitAsync(AsyncCallable, Executor)
边栏推荐
- [ 漏洞复现篇 ] yapi 代码执行 getshell 漏洞复现详解
- C# 一周入门高级编程之《C#-接口》Day Two
- "Swordsman Offer" brush questions print from 1 to the largest n digits
- FusionAccess软件架构、FusionAccess必须配置的四个组件、桌面发放流程、虚拟机组类型、桌面组类型
- ceph简介
- 牛客 - 最佳直播时间 (差分)
- HCIA实验(07)
- mysql存生僻字奇怪问题,mysql为什么不能辨别mb4字符?
- 【TPC-DS】25张表的详细介绍,SQL的查询特征
- Redis的基础与django使用redis
猜你喜欢
随机推荐
品牌方发行NFT时,应如何考量实用性?
mysql存生僻字奇怪问题,mysql为什么不能辨别mb4字符?
tolower函数
[Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
pyspark---low frequency feature processing
Redisson实现分布式锁
001-进程与线程
“==”和equals的区别
Neo4j 4.X:导入OWL文件
推荐系统-排序层-模型:Wide&Deep
数据监控平台
mysql服务器上的mysql这个实例中表的介绍
mysql备份时的快照原理
熊市中预言机,牛市中的战斗机,藏宝计划起飞,坐稳扶好!
Mysql如何对两张表的相同字段,同时查询两张数据表
推荐系统-排序层-特征工程:用户特征、物品特征
DeFi明斯基时刻:压力测试与启示
ArcEngine(二)加载地图文档
Evaluate:huggingface评价指标模块入门详细介绍
Karatsuba大数乘法的Verilog实现