ListenableFuture

1. 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 and ListenableFuture variants of their methods.

2. Callbacks

A FutureCallback<V> implements two methods:

  • onSuccess(V), the action to perform if the future succeeds, based on its result
  • onFailure(Throwable), the action to perform if the future fails, based on the failure

3. Creation

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(); // escaped the explosion!
  }
});

4.Application

Method Description See also
transformAsync(ListenableFuture<A>, AsyncFunction<A, B>, Executor)* Returns a new ListenableFuture whose result is the product of applying the given AsyncFunction to the result of the given ListenableFuture. transformAsync(ListenableFuture<A>, AsyncFunction<A, B>)
transform(ListenableFuture<A>, Function<A, B>, Executor) Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given ListenableFuture.
对于ListenableFuture的返回值进行转换
transform(ListenableFuture<A>, Function<A, B>)
allAsList(Iterable<ListenableFuture<V>>) Returns a ListenableFuture whose value is a list containing the values of each of the input futures, in order. If any of the input futures fails or is cancelled, this future fails or is cancelled.
对多个ListenableFuture的合并,返回一个当所有Future成功时返回多个Future返回值组成的List对象.当其中一个Future失败或者取消的时候,将会进入失败或者取消
allAsList(ListenableFuture<V>...)
successfulAsList(Iterable<ListenableFuture<V>>) Returns a ListenableFuture whose value is a list containing the values of each of the successful input futures, in order. The values corresponding to failed or cancelled futures are replaced with null.
和allAsList相似,唯一差别是对于失败或取消的Future返回值用null代替,不会进入失败或者取消流程
successfulAsList(ListenableFuture<V>...)
immediateFuture/immediateCancelledFuture 立即返回一个待返回值的ListenableFuture
makeChecked 将ListenableFuture转换成CheckedFuture.CheckedFuture是一个ListenableFuture,其中包含了多个版本的get方法,方法声明抛出检查异常.这样使得创建一个在执行逻辑中可以抛出异常的Future更加容易
JdkFutureAdapters.listenInPoolThread(future) 提供了将JDK Future转换为ListenableFuture的接口函数

results matching ""

    No results matching ""