在FutureCallback中启动ListenableFuture并在完成所有操作后回调

时间:2014-12-18 12:37:32

标签: java guava

我试图为ListenableFutures设置一个嵌套的回调层,如下所示:

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

ListenableFuture<A> futureA = service.submit(() -> a.doSomething());

Futures.addCallback(futureA, new FutureCallback<A>() {
    @Override
    public void onSuccess(A result) {
         ListenableFuture<B> futureB = service.submit(() -> b.doSomething(result)
    }
});

如果futureAfutureB完成后如何添加回调?

这是一个简单的示例,但我正在寻找可能有多层ListenableFuture的解决方案。

1 个答案:

答案 0 :(得分:2)

可能选择使用allAsList创建新的未来。 (我假设您不介意同时启动ab。)

//No idea how A and B are related, so I assume Object
ListenableFuture<List<? extends Object>> futureAB = Futures.allAsList(futureA, futureB);
Futures.addCallback(futureAB, ...);

更新后:

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

ListenableFuture<A> futureA = service.submit(() -> a.doSomething());

Futures.addCallback(futureA, new FutureCallback<A>() {
    @Override
    public void onSuccess(final A result) {
         ListenableFuture<B> futureB = service.submit(() -> b.doSomething(result);
         Futures.addCallback(futureB, new FutureCallback<B>() {
              ©Override
              public void onSuccess(final B resultB) {
                  //Do something with result and resultB.
              }
         });
    }
});