异步操作的结果列表

luk*_*ell 2 java concurrency asynchronous guava

我的目标是从10(或其他任意数量)的异步操作中获取结果列表.

我正在使用com.google.guava并发中的实用程序,如果有人可以慷慨地指出我正确的方向,我会非常感激.

在示例中,我正在尝试获取一个列表successfulBombs(Bomb几乎是一个空对象,但在创建模拟服务调用执行问题时有随机概率抛出问题)

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
List<ListenableFuture<Bomb>> bombs;
ListenableFuture<List<Bomb>> successfulBombs;
Run Code Online (Sandbox Code Playgroud)

编辑:

这是我到目前为止所提出的,但即使它应该有一些成功的元素,列表也是空的......我无法辨别为什么

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
List<ListenableFuture<Bomb>> bombs = new ArrayList<ListenableFuture<Bomb>>();
for(int i=0;i<10;i++)
{
    ListenableFuture<Bomb> bomb = service.submit(new Callable<Bomb>(){
        public Bomb call() throws Problem
        {
            return craftBomb();
        }
    });
}
ListenableFuture<List<Bomb>> successfulBombs = Futures.successfulAsList(bombs);
Futures.addCallback(successfulBombs, new FutureCallback<List<Bomb>>(){
    public void onSuccess(List<Bomb> bombs)
    {
        System.out.println("My successful bombs");
        for(Bomb b : bombs)
        {
            System.out.println(b);
        }
    }
    public void onFailure(Throwable thrown)
    {
        System.err.println("There was a problem making this bomb.");
    }
});
Run Code Online (Sandbox Code Playgroud)

在结束我正在寻找的:

  • 用于启动异步操作的正确模式
  • 为结果操作收集列表
  • 使用番石榴框架收集成功操作列表

Col*_*inD 6

该列表为空,因为您从未添加任何内容bombs.你正在传递一个空列表Futures.successfulAsList.