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

  1. Start with Completed result 2
  2. Do this Double the result
  3. Result 4
A successful stage passes its value to the transformation.

Apply it to a real problem

  1. Start with One completed count of 3 and one failed job
  2. Do this Double successes, recover failures as zero
  3. Result 6 and 0
The fallback supplies a reportable value when the job fails.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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);
        }
    }
}
Output
6
0

Official Java documentation