Skip to content

Instantly share code, notes, and snippets.

@guss77
Created March 26, 2018 04:52
Show Gist options
  • Save guss77/b8623ab7586f154895aa33248872ae21 to your computer and use it in GitHub Desktop.
Save guss77/b8623ab7586f154895aa33248872ae21 to your computer and use it in GitHub Desktop.
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