CompletableFuture helper class
package tech.greenfield.util.concurrent; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
public class Futures { | |
static class Thrower { | |
static Throwable except; | |
Thrower() throws Throwable { | |
throw except; | |
} | |
public static void spit(Throwable t) { | |
except = t; | |
try { | |
Thrower.class.newInstance(); | |
} catch (InstantiationException | IllegalAccessException e) { } | |
} | |
} | |
public static <T,E extends Throwable> Function<Throwable, ? extends T> on(Class<E> errType, Function<E, ? extends T> fn) { | |
return t -> { | |
if (!errType.isInstance(t)) | |
Thrower.spit(t); | |
@SuppressWarnings("unchecked") E e = (E)t; | |
return fn.apply(e); | |
}; | |
} | |
public static <T> CompletableFuture<T> failedFuture(Throwable thr){ | |
CompletableFuture<T> f = new CompletableFuture<T>(); | |
f.completeExceptionally(thr); | |
return f; | |
} | |
public static <T> CompletableFuture<T> successfulFuture(T value) { | |
CompletableFuture<T> f = new CompletableFuture<T>(); | |
f.complete(value); | |
return f; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment