CompletableFuture 无需阻塞即可获得结果
CompletableFuture get result without blocking
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()
方法时它会阻塞并且我浪费了并发的好处,知道如何做到这一点吗?
这是一个提交所有任务然后获取结果的实现,return在第一个 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
将 return。
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()
方法时它会阻塞并且我浪费了并发的好处,知道如何做到这一点吗?
这是一个提交所有任务然后获取结果的实现,return在第一个 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
将 return。