Created
February 20, 2021 11:59
-
-
Save benjiman/a7de0633b502590648c507e5dce4c74a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.benjiweber; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.function.Supplier; | |
public class ConditionalFuture { | |
public static void main(String... args) throws ExecutionException, InterruptedException { | |
var i = new AtomicInteger(0); | |
var future = | |
run(() -> System.out.println("Running... " + i.get())) | |
.when(() -> i.incrementAndGet() < 10) ; | |
future.get(); | |
} | |
private static <T> Until<T> run(Runnable op) { | |
return condition -> CompletableFuture | |
.runAsync(() -> { | |
if (!condition.get()) { | |
throw new Done(); | |
} | |
}) | |
.thenRun(op) | |
.thenCompose(__ -> ConditionalFuture.<T>run(op).when(condition)) | |
.exceptionally(e -> null); | |
} | |
static class Done extends RuntimeException { | |
public synchronized Throwable fillInStackTrace() { | |
return null; | |
} | |
} | |
interface Until<T> { | |
CompletableFuture<T> when(Supplier<Boolean> condition); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment