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;
}
In the above code I want to create mxList.size()
CompletableFuture
, execute each. If the result of any of them is true
I want to break the loop, when I used the get()
method it blocks and I waste the benefit of concurrency, any idea about how to do that?
CompletionService
. Make the tasks interruptible (otherwise you gain very little) - when you recieve an invalid result then cancel all the remaining tasks. There's a good example in the documentation forExecutorCompletionService
.CompletableFuture.thenAccept
to dump the results into aBlockingQueue
and having your main threadtake()
and process the results as they become available - hey, this is exactly whatCompletionService
does.verifier.thenApply(isvalid -> isvalid)
?