大多数Futures方法需要它
ListenableFuture使用起来更简单
公共方法的提供者不需要提供方法中变量
接口
传统future代码了异步计算的结果,异步计算很可能还没有完成,一个Future能够用来处理正在进行中的计算
ListenableFuture允许注册回调方法,一旦完成计算后,回调就会执行。或者回调已经完成就立即执行。这种方式能够有效支持传统Future接口不能处理的很多操作
ListenableFuture添加的基本操作是 addListener(Runnable,Executor),指出当特定的计算完成后,
指定的runnable任务将在特定的执行器上执行。
添加回调
大多数用户喜欢使用Futures.addCallback(ListenableFuture<V>,FutureCallback<V>,Executor)
或者使用MoreExecutors.directExecutor(),为了能够使回调更快更轻,实现了下面两个方法:
onSuccess(V) 结果如果执行成功,执行行为
onFailure(Throwable),结果执行失败,执行失败相关行为
创建
JDK ExecutorService.submit(Callable),Guava提供了ListeningExecutorService接口,返回
ListenableFuture 而 ExecutorService返回原来的Future,将ExecutorService转成
ListeningExecutorService
使用MoreExecutors.listeningDecorator(ExecutorService)
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<Explosion> explosion = service.submit(new Callable<Explosion>() {
public Explosion call() {
Explosion explosion1 = new Explosion();
return explosion1.getExplosion();
}
});
//void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback, Executor executor)
Futures.addCallback(explosion, new FutureCallback<Explosion>() {
public void onSuccess(@Nullable Explosion explosion) {
System.out.println("success");
}
public void onFailure(Throwable throwable) {
System.out.println("error");
}
}, service);
ListenableFuture<RowKey> rowKeyFuture=indexService.lookUp(query);
AsyncFunction<RowKey,QueryResult> queryFuction=new AsyncFunction<RowKey, QueryResult>() {
public ListenableFuture<QueryResult> apply(RowKey rowKey) throws Exception {
return null;
}
};
ListenableFuture<QueryResult> queryFuture=Futures.transformAsync(rowKeyFuture,queryFuction,queryExecutor);
ListenableFuture还能够支持其他多种方法
Service对象带有状态,有方法进行启动和停止,如webservices RPC services,timers实现 Service接口
Service提供了许多模版式方法进行状态管理和同步控制
Service的生命周期有
Service.State.NEW
Service.State.STARTING
Service.State.RUNNING
Service.State.STOPPING
Service.State.TERMINATED
关闭的服务不能再重新启动,如果在启动中,运行中,停止中失败,状态将变成Service.State.FAILED
一个服务可以异步启动使用startAsync(),如果service是NEW,会使用一个独立的地方创建应用服务。
停止一个服务使用stopAsync(),可以多次调用该方法,可以避免关闭时出现的处理竞争关系
Service也提供了过度方法等待service的结束
异步使用addListener(),每个状态转移的过程中都会触发监听
同步使用awaitRunning(),是不可以打断的,抛出不检测的异常,service启动后立即返回,如果启动失败,
抛出非法状态异常
实现类
AbstractIdleService
有startup和shutdown行为的执行,可以在子类中具体实现相关的行为
AbstractExecutionThreadService
AbstractScheduledService
AbstractService 写自己的实现类,直接覆盖抽象类中方法就可以了
使用ServiceManager
用来管理Services
startAsync启动所有管理的服务
stopAsync()关闭所有管理的Services
addListener() 添加了一个ServiceManager.Listener,在大多数状态转移中会被调用
awaitHealthy()等待所有的servcies到达running状态
awaitStopped 等待所有services到达终态