Concurrency is a hard problem, but it is significantly simplified by working with powerful and simple abstractions. To simplify matters, Guava extends the Future
interface of the JDK with ListenableFuture
.
We strongly advise that you always use ListenableFuture
instead of Future
in all of your code, because:
- Most
Futures
methods require it. - It's easier than changing to
ListenableFuture
later. - Providers of utility methods won't need to provide
Future
andListenableFuture
variants of their methods.
并发是一个很难解决的问题,但是通过强有力而简单抽象又可以变成非常容易。为了简化问题,,Google Guava 工具类通过ListenableFuture 继续JDK Future 接口实现。
Google Guava 强烈建议用户使用ListenableFuture来替代JDK 的Future.
Future Interface :
A traditional Future
represents the result of an asynchronous computation:a computation that may or may not have finished producing a result yet.
A Future
can be a handle to an in-progress computation, a promise from a service to supply us with a result.
A ListenableFuture
allows you to register callbacks to be executed once the computation is complete, or if the computation is already complete, immediately.
This simple addition makes it possible to efficiently support many operations that the basic Future
interface cannot support.
The basic operation added by ListenableFuture
is addListener(Runnable, Executor)
, which specifies that when the computation represented by this Future
is done, the specified Runnable
will be run on the specified Executor
.
传统Future 代表着一个异步计算的结果。一个异步计算也有有结果,也许根本就没有结果返回。
一个Future可以处理正在进行的计算,一个Promise 可以告诉异步计算的结果。
在Google Guava 中一个ListenableFuture 允许用户注册一个回调函数,这个回调函数会在异步计算完成时被调用。或者异步计算已经完成时,立即被调用。
注册一个回调函数可以高效的支持很多操作,这个是JDK Future 接口不提供的功能。
在ListenableFuture接口中有一个addListener(Runnable,Executor)方法。
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListenableFuture<Integer> f = service.submit(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(1000);
System.out.println("Sleep......");
return new Integer(99);
}
});
Futures.addCallback(f, new FutureCallback<Integer>() {
public void onFailure(Throwable arg0) {
// TODO Auto-generated method stub
}
public void onSuccess(Integer arg0) {
System.out.println("result:" + arg0);
}
});
参考链接:
Guava ListenableFuture
https://github.com/google/guava/wiki/ListenableFutureExplained