Created
October 28, 2016 02:21
-
-
Save rex-sheridan/31f777e00d0115fc04a22675d76c7afe to your computer and use it in GitHub Desktop.
What if you don't want to decide right away when the CompletableFuture will begin executing?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.Executor; | |
import java.util.function.Function; | |
import java.util.function.Supplier; | |
public abstract class DeferredCompletableFuture<T> | |
implements Function<Executor, CompletableFuture<T>>, Supplier<CompletableFuture<T>> { | |
private static class SupplierDeferredCompletableFuture<T> extends DeferredCompletableFuture<T> { | |
Supplier<T> supplier; | |
private SupplierDeferredCompletableFuture(Supplier<T> supplier) { | |
this.supplier = supplier; | |
} | |
public CompletableFuture<T> executeSync() { | |
return executeAsync(Runnable::run); | |
} | |
public CompletableFuture<T> executeAsync() { | |
return CompletableFuture.supplyAsync(supplier); | |
} | |
public CompletableFuture<T> executeAsync(Executor executor) { | |
return CompletableFuture.supplyAsync(supplier, executor); | |
} | |
} | |
private static class RunnableDeferredCompletableFuture extends DeferredCompletableFuture<Void> { | |
Runnable runnable; | |
private RunnableDeferredCompletableFuture(Runnable runnable) { | |
this.runnable = runnable; | |
} | |
public CompletableFuture<Void> executeSync() { | |
return executeAsync(Runnable::run); | |
} | |
public CompletableFuture<Void> executeAsync() { | |
return (CompletableFuture<Void>) CompletableFuture.runAsync(runnable); | |
} | |
public CompletableFuture<Void> executeAsync(Executor executor) { | |
return (CompletableFuture<Void>) CompletableFuture.runAsync(runnable, executor); | |
} | |
} | |
public abstract CompletableFuture<T> executeSync(); | |
public abstract CompletableFuture<T> executeAsync(); | |
public abstract CompletableFuture<T> executeAsync(Executor executor); | |
public static <U> DeferredCompletableFuture<U> with(Supplier<U> supplier) { | |
return new SupplierDeferredCompletableFuture<U>(supplier); | |
} | |
public static DeferredCompletableFuture<Void> with(Runnable runnable) { | |
return new RunnableDeferredCompletableFuture(runnable); | |
} | |
@Override | |
public CompletableFuture<T> apply(Executor executor) { | |
return executeAsync(executor); | |
} | |
@Override | |
public CompletableFuture<T> get() { | |
return executeAsync(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment