Skip to content

Instantly share code, notes, and snippets.

@guss77 guss77/Futures.java
Created Mar 26, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.