Created
January 9, 2018 04:15
-
-
Save mohansunkara/9d32bb08ec6e9eb18f88ff4527dccf9f to your computer and use it in GitHub Desktop.
Sample code for short circuiting CompletableFuture chain based on solution @ https://stackoverflow.com/questions/48145264/shortcut-chain-of-completablefuture-based-on-a-condition.
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
@RunWith(JUnit4.class) | |
public class ExceptionHandlingTests { | |
class ShortCircuitCF<T> { | |
final CompletableFuture<T> result = new CompletableFuture<>(); | |
final CompletableFuture<T> notCompleted = new CompletableFuture<>(); | |
CompletableFuture<T> propagate(T value) { | |
result.complete(value); | |
return notCompleted; | |
} | |
CompletableFuture<T> complete(T value) { | |
return CompletableFuture.completedFuture(value); | |
} | |
CompletableFuture<T> getResult() { | |
return result; | |
} | |
} | |
@Test | |
public void test1() { | |
for(int shortCutAt: IntStream.range(0, 4).toArray()) { | |
System.out.println("Example execution with " | |
+ (shortCutAt == 0 ? "no shortcut" : "shortcut at " + shortCutAt)); | |
ShortCircuitCF<Integer> result = new ShortCircuitCF<>(); | |
CompletableFuture.completedFuture(null).thenCompose(justVoid -> { // runAsync | |
System.out.println("Completing result1. Result: " + result.getResult().isDone()); | |
if (shortCutAt == 1) { | |
return result.propagate(10); | |
} | |
return result.complete(null); | |
}).thenCompose(x -> { | |
System.out.println("Completing result2. Result: " + result.getResult().isDone()); | |
if (shortCutAt == 2) { | |
return result.propagate(10); | |
} | |
return result.complete(5); | |
}).thenCompose(x -> { | |
System.out.println("Completing result3. Result: " + result.getResult().isDone()); | |
if (shortCutAt == 3) { | |
return result.propagate(10); | |
} | |
return result.complete(5); | |
}).applyToEither(result.getResult(), Function.identity()) | |
.thenAccept(fr -> System.out.println("final result: " + fr)); | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment