CompletableFuture列表等待所有将来的发行

时间:2019-04-25 21:07:16

标签: java-8 completable-future

我有下面的CompletableFuture管道列表

for (Integer unit : getIds()) {
        futureList.add(CompletableFuture.completedFuture(unit)
            .thenApply(id -> CompletableFuture
                .completedFuture(service.get1(id))
                .thenCombineAsync(CompletableFuture.completedFuture(b), (a, df1) -> 
                    CompletableFuture.completedFuture(service.validate(Optional.ofNullable(a),c, 
                            b, dealerCode))
                    .thenApplyAsync(status -> CompletableFuture.completedFuture(b))
                    .thenCombineAsync(CompletableFuture.completedFuture(a), (b1, a1) -> 
                        service.mapToTrans(Optional.ofNullable(a), b, c))
                    .handle((response, exception) -> {
                        if(exception == null) {
                            return response;
                        }
                        else {
                            handler.handleException(exception, results);
                            return null;
                        }
                    })
                    .thenApplyAsync(t -> service.submitRequest(Optional.ofNullable(a), c))
                    .thenApplyAsync((t) -> service.saveTransaction(Optional.ofNullable(t)))
                    .thenAccept(result1 -> results.add(result1))
                )
                .handle((response, exception) -> handleStage(response, exception, results))
            )
            .handle((response, exception) -> handleStage(response, exception, results))
            );
    }

结果数组保存所有期货的结果。在主要方法中,这就是我等待所有期货完成的方式

CompletableFuture<Void> allFutures = CompletableFuture
            .allOf(futureList.toArray(new CompletableFuture[futureList.size()]));
CompletableFuture<List<Object>> allFutureExec = allFutures.thenApply(v -> {
            return futureList.stream().map(pg-> pg.join()).collect(Collectors.toList());
        });
allFutureExec.get();

“结果”列表应该包含所有未来链的结果,但是我可以看到主线程没有等待所有阶段都执行。尽管从日志中可以看到所有期货都已执行,但结果列表仅包含很少的期货结果。请让我知道这是否是等待所有期货完成的正确方法。

UPDATE-1

for (Integer unit : getIds()) {
        futureList.add(CompletableFuture
                .completedFuture(service.get1(unit))
                .thenCombine(CompletableFuture.completedFuture(td), (vd, dealerInfo1) -> 
                    CompletableFuture.completedFuture(service.validate(Optional.ofNullable(vd),sd, 
                        td))
                    .thenApply(status -> CompletableFuture.completedFuture(service.mapToTrans
                            (Optional.ofNullable(vd), td,trade, userCredential))
                    .thenApplyAsync(transaction -> CompletableFuture.completedFuture(service.submit(Optional.ofNullable(vd),transaction))
                    .thenApply((transaction1) -> service.saveTransaction(Optional.ofNullable(transaction1)))
                    .thenApply(result1 -> results.add(result1)))))
        );      

    }

0 个答案:

没有答案