Recover a failed asynchronous result in Java
A successful stage transforms its value. A failed stage skips the transformation and exceptionally supplies a fallback before join returns.
A simple example
Double the result
- Start with Completed result 2
- Do this Double the result
- Result 4
Apply it to a real problem
- Start with One completed count of 3 and one failed job
- Do this Double successes, recover failures as zero
- Result 6 and 0
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
var ok = CompletableFuture.completedFuture(3);
var failed = CompletableFuture.<Integer>failedFuture(new IllegalStateException("offline"));
for (var stage : List.of(ok, failed)) {
int total = stage.thenApply(count -> count * 2).exceptionally(error -> 0).join();
System.out.println(total);
}
}
}
6 0