CompletableFuture supply与Stream.map()异步

时间:2018-11-22 16:33:55

标签: concurrency

伙计们!我有一个问题:这段代码是做什么的:

Collection<Contract.class> contracts = fillTheCollectionFromDb();
contracts.stream().filter(condition)
                  .map(contractItem ->
                       CompletableFuture.supplyAsync(() -> 
                           {T result = getAnotherDataFromDb(contractItem); 
                            return result;}, Executor.class)
                  )//end .map
                  .map(CompletableFuture::join).collect(Collectors.toList());

1 个答案:

答案 0 :(得分:0)

此代码等效于:

Collection<Contract> contracts = fillTheCollectionFromDb();
contracts.stream().filter(condition)
              .map(this::getAnotherDataFromDb)
              .collect(Collectors.toList());

要使该程序真正并行,应对其进行修改。首先,并行启动对数据库的所有请求:

Collection<Contract> contracts = fillTheCollectionFromDb();
List<CompletableFuture> futures = contracts.stream().filter(condition)
              .map(contractItem ->
                   CompletableFuture.supplyAsync(
                         ()->getAnotherDataFromDb(contractItem),
                       executor)
              )//end .map
              .collect(Collectors.toList());

然后才收集所有结果:

List results = futures.stream
      .map(CompletableFuture::join)
      .collect(Collectors.toList());