rpc.turbo.util.concurrent.FutureUtils Maven / Gradle / Ivy
package rpc.turbo.util.concurrent;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public class FutureUtils {
public static CompletableFuture withFailover(CompletableFuture future,
Supplier> failover) {
CompletableFuture futureWithFailover = future.newIncompleteFuture();
future.whenComplete((result, throwable) -> {
if (throwable != null) {
failover.get().whenComplete((r, t) -> {
if (t != null) {
futureWithFailover.completeExceptionally(t);
} else {
futureWithFailover.complete(r);
}
});
} else {
futureWithFailover.complete(result);
}
});
return futureWithFailover;
}
}