Skip to content

Instantly share code, notes, and snippets.

@benjiman
Created February 20, 2021 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjiman/a7de0633b502590648c507e5dce4c74a to your computer and use it in GitHub Desktop.
Save benjiman/a7de0633b502590648c507e5dce4c74a to your computer and use it in GitHub Desktop.
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