From ee747afaac788be13f3585ba43a7cf00046aac46 Mon Sep 17 00:00:00 2001 From: Andrea Cavalli Date: Wed, 24 Jun 2020 17:44:51 +0200 Subject: [PATCH] Update CompletableFutureUtils.java --- .../future/CompletableFutureUtils.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/main/java/org/warp/commonutils/concurrency/future/CompletableFutureUtils.java b/src/main/java/org/warp/commonutils/concurrency/future/CompletableFutureUtils.java index eb4db36..8d69921 100644 --- a/src/main/java/org/warp/commonutils/concurrency/future/CompletableFutureUtils.java +++ b/src/main/java/org/warp/commonutils/concurrency/future/CompletableFutureUtils.java @@ -10,7 +10,9 @@ import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; import java.util.function.Consumer; +import java.util.function.Supplier; import java.util.stream.Collectors; public class CompletableFutureUtils { @@ -145,4 +147,32 @@ public class CompletableFutureUtils { public static void forEach(CompletableFuture>> futureList, Consumer consumer) { futureList.join().parallelStream().map(CompletableFuture::join).forEach(consumer); } + + public static CompletableFuture catchUncheckedExceptions(Supplier> supplier) { + try { + return supplier.get(); + } catch (Exception exception) { + return CompletableFuture.failedFuture(exception); + } + } + + public static CompletableFuture runSequence(Collection> collection) { + if (collection.isEmpty()) { + return CompletableFuture.completedFuture(null); + } else { + var result = new CompletableFuture(); + for (CompletableFuture completableFuture : collection) { + result = result.thenCompose(x -> completableFuture.thenRun(() -> {})); + } + return result; + } + } + + public static CompletableFuture runSequenceAsync(Collection> collection, ExecutorService executorService) { + var result = CompletableFuture.completedFuture(null); + for (CompletableFuture completableFuture : collection) { + result = result.thenComposeAsync(x -> completableFuture.thenRun(() -> {}), executorService); + } + return result; + } }