Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return CompletableFuture<Void> or CompletableFuture<?>?

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?

  • CompletableFuture itself returns CompletableFuture<Void> from many of its methods.
  • java.nio has a Future<Void> in AsynchronousSocketChannel: Future<Void> connect(SocketAddress remote).
  • On the other hand, java.util.concurrent classes like ExecutorService and ScheduledExecutorService return Future<?>: for instance, with Future<?> submit(Runnable task).

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

like image 713
John Kugelman Avatar asked Dec 11 '15 22:12

John Kugelman


1 Answers

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.

like image 73
John Kugelman Avatar answered Sep 17 '22 17:09

John Kugelman