John Kugelman John Kugelman - 2 months ago 34
Java Question

Return CompletableFuture<Void> or CompletableFuture<?>?

I want to write an asynchronous method that returns a

. The only purpose of the future is to track when the method is complete, not its result. Would it be better to return
? Is there a reason to prefer one or the other, or are they interchangeable?

Note that I'm only asking about return types, not parameter lists, variable declarations, or other contexts.


It is best to use CompletableFuture<Void>.

According to this answer found by Sotirios Delimanolis, Future<?> is a minor API flaw. In Java 6 the submit() method used a Future<Object> internally, and so its return type was set to Future<?>. In Java 7 the implementation changed to use Future<Void> internally, but it was too late to change the API so the return value stayed as Future<?>.

Newer Java APIs use Future<Void> and CompletableFuture<Void>. Those are the examples we should follow.