John Kugelman John Kugelman - 1 year ago 107
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download