guava笔记三: Concurrency 简单介绍
Guava Concurrency是什么
Concurrency是一个很困难的问题,但是可以使用抽象的方法大大简化使用。Guava继承Future
接口,定义了接口ListenableFuture
。
Guava官方建议尽量使用ListenableFuture来代替Future,因为:
* Future
大多数方法Listenable可以适用
* 后期再使用ListenableFuture
比较麻烦
* 不需要根据Future
和ListenableFuture
的差异增加工具类.
ListenableFuture
和Future
的区别是什么
从接口来看,主要增加了addListener
方法,用来实现当future完成的时候,就使用Executor来执行runable
Guava Concurrency支持的callback
如果简单实用,那么可以使用默认的MoreExecutors.sameThreadExecutor()
。不过更多可以选择的是Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor)
.一个FutureCallback<V>主要实现两个方法:
onSuccess(V)
*,成功之后做什么
onFailure(Throwable)`失败了做什么
*
创建方法
对应于JDK本身的ExecutorService.submit(Callable)
方式创建异步计算,返回以恶搞Future
,Guava提供了一个ListeningExecutorService
接口,返回ListenableFutre
.可以使用MoreExecutors.listeningDecorator(ExecutorService)
把ExecutorService
转化成ListeningExecutorService
.
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<Explosion> explosion = service.submit(new Callable<Explosion>(){
public Explosion call(){
return pushBigRedButton;
}
});
Futures.addCallback(explosion, new FutureCallback<Explosion>(){
// we want this handler to run immediately after we push the big red button
public void onSuccess(Explosion explosion){
walkAwayFrom(explosion);
}
public void onFailure(Throwable thrown){
battleArchNemesis();//escape the explosion
}
});
应用场景
使用ListenableFuture最主要的场景就是异步执行chain.
ListenableFuture<RowKey> rowKeyFuture = indexService.lookup(query);
AsyncFunction<RowKey, QueryResult> queryFunction =
new AsyncFunction<RowKey, QueryResult>(){
public ListenableFuture<QueryResult> apply(RowKey rowKey){
return dataService.read(rowKey);
}
};
ListenableFuture<QueryResult> queryFuture = Futures.transformAsync(rowKeyFuture, queryFunction, queryExecutor);
ListenableFuture的其他方法:
Method | Description |
---|---|
transformAsync(ListenableFuture<A>, AsyncFunction<A, B>, Executor)* | 返回一个新的ListenableFuture,并且它的参数是使用AsyncFunction(ListenableFuture)的结果。 |
transform(ListenableFuture<A>, Function<A, B>, Executor) | 这个是非异步的function计算结果作为参数的ListenableFuture |
allAsList(Iterable<ListenableFuture<V>>) | 返回一个ListenableFuture,结果是输入的future.当一个失败或者取消,就会停止了.不太理解 |
successfulAsList(Iterable<ListenableFuture<V>>) | 这个是把failed和cancelled的future结果替换成null,不会停止 |