我试图为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)
}
});
如果futureA
和futureB
完成后如何添加回调?
这是一个简单的示例,但我正在寻找可能有多层ListenableFuture
的解决方案。
答案 0 :(得分:2)
可能选择使用allAsList
创建新的未来。 (我假设您不介意同时启动a
和b
。)
//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.
}
});
}
});