From f4536b6a56ab69f3eef9aa00f94d96fffc259279 Mon Sep 17 00:00:00 2001 From: HenrikJannsen Date: Wed, 7 Dec 2022 11:47:51 -0500 Subject: [PATCH] Add CompletableFutureUtil Signed-off-by: HenrikJannsen --- .../common/util/CompletableFutureUtil.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 common/src/main/java/bisq/common/util/CompletableFutureUtil.java diff --git a/common/src/main/java/bisq/common/util/CompletableFutureUtil.java b/common/src/main/java/bisq/common/util/CompletableFutureUtil.java new file mode 100644 index 0000000000..7c885ab4db --- /dev/null +++ b/common/src/main/java/bisq/common/util/CompletableFutureUtil.java @@ -0,0 +1,57 @@ +/* + * This file is part of Bisq. + * + * Bisq is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at + * your option) any later version. + * + * Bisq is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public + * License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Bisq. If not, see . + */ + +package bisq.common.util; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +//todo +public class CompletableFutureUtil { + public static CompletableFuture> allOf(Collection> collection) { + //noinspection unchecked + return allOf(collection.toArray(new CompletableFuture[0])); + } + + public static CompletableFuture> allOf(Stream> stream) { + return allOf(stream.collect(Collectors.toList())); + } + + public static CompletableFuture> allOf(CompletableFuture... list) { + CompletableFuture> result = CompletableFuture.allOf(list).thenApply(v -> + Stream.of(list) + .map(future -> { + // We want to return the results in list, not the futures. Once allOf call is complete + // we know that all futures have completed (normally, exceptional or cancelled). + // For exceptional and canceled cases we throw an exception. + T res = future.join(); + if (future.isCompletedExceptionally()) { + throw new RuntimeException((future.handle((r, throwable) -> throwable).join())); + } + if (future.isCancelled()) { + throw new RuntimeException("Future got canceled"); + } + return res; + }) + .collect(Collectors.toList()) + ); + return result; + } +}