CompletableFuture获得结果而不会阻塞

时间:2018-11-08 19:03:56

标签: java concurrency completable-future

private static boolean validateSMTP(final ArrayList mxList, String address) throws ExecutionException, InterruptedException {
  ExecutorService pool = Executors.newFixedThreadPool(mxList.size());
  List<CompletableFuture<Boolean>> allVerifiers = new ArrayList<>();
    for (int mx = 0; mx < mxList.size(); mx++) {
        CompletableFuture<Boolean> verifier = createAsyncVerifier((String) mxList.get(mx), address, pool);
        verifier.thenApply(isvalid -> isvalid);
        verifier.get();
    }
  return false;
}

在上面的代码中,我要创建mxList.size() CompletableFuture,分别执行。如果其中任何一个的结果是true,我想打破循环,那么当我使用get()方法时,它会阻塞并且浪费了并发的好处,关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

这是一个提交所有任务然后获取结果的实现,并返回第一个true结果:

private static boolean validateSMTP(final ArrayList<String> mxList, String address)
        throws ExecutionException, InterruptedException {

    ExecutorService pool = Executors.newFixedThreadPool(mxList.size());

    return mxList.stream()
            .map(mx -> createAsyncVerifier(mx, address, pool))
            .collect(Collectors.toList())
            .stream()
            .map(CompletableFuture<Boolean>::join)
            .filter(b -> b)
            .findFirst()
            .orElse(Boolean.FALSE);
}

.collect(Collectors.toList())确保提交所有任务。在第二个流中,调用join,但这不会引起不必要的等待,因为所有任务都已提交。

findFirst将在第一个元素通过过滤器后立即返回。