Return CompletableFuture<Void> or CompletableFuture<?>?

John Kugelman picture John Kugelman · Dec 11, 2015 · Viewed 39.4k times · Source

I want to write an asynchronous method that returns a CompletableFuture. The only purpose of the future is to track when the method is complete, not its result. Would it be better to return CompletableFuture<Void> or CompletableFuture<?>? 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.

Answer

John Kugelman picture John Kugelman · Aug 17, 2016

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.