Type Handling with anyOf
You'll learn how to safely work with anyOf's generic Object return type and manage futures that complete with different types.
The Type Challenge
When you use CompletableFuture.anyOf(), it returns CompletableFuture<Object> because Java doesn't know which of your potentially heterogeneous futures will finish first. If you're racing a CompletableFuture<String> against a CompletableFuture<Integer>, the compiler can only guarantee the result will be some object.
Analogy: It's like a race where contestants carry different prizes—you know someone will arrive first, but you don't know whether you'll receive a trophy or a medal until they cross the line.
Safe Casting Strategies
You have several approaches:
1. Homogeneous Futures (Best Case)
If all futures return the same type, cast directly:
CompletableFuture<String> cf1 = CompletableFuture.completedFuture("A");
CompletableFuture<String> cf2 = CompletableFuture.completedFuture("B");
CompletableFuture.anyOf(cf1, cf2)
.thenApply(result -> (String) result) // Safe: all are Strings
.thenAccept(str -> System.out.println(str));
2. Type Checking with instanceof
For heterogeneous futures, check types before casting:
CompletableFuture.anyOf(stringFuture, intFuture)
.thenAccept(result -> {
if (result instanceof String) {
String s = (String) result;
} else if (result instanceof Integer) {
Integer i = (Integer) result;
}
});
3. Wrapper Types
Create a common interface or sealed class hierarchy to unify disparate types before passing to anyOf.
Avoiding Runtime Errors
Never blindly cast anyOf results—ClassCastException is a real risk. Always validate types or design your futures to return compatible types from the start.
Key Takeaway: anyOf returns CompletableFuture<Object>, requiring explicit casting; use homogeneous future types when possible, or employ instanceof checks to safely handle heterogeneous results and avoid ClassCastException at runtime.