javavert.x

what is Future<void>?


I have following code snippet.

import io.vertx.core.Future;
public void start(Future<void> fut){

  /*
  some code
  */
  fut.complete()
}

Why is the **Future** used here?

Solution

  • Future<Void> is a future result of an execution that returns no value.

    That would be typically the result of invoking the run method of a Runnable.

    The normal void call looks like (see r.run()):

    Runnable r = () -> System.out.println("running");
    r.run();
    

    When such a call is done asynchronously, such as via an executor service or a completable future, it turns into a future:

    Future<Void> future = CompletableService.runAsync(r);
    

    It's just a future of an execution that returns no result. This "future" contains information about the execution, even though it has no "return" value (such as what Future<Object> would have).

    You can get information about the asynchronous execution. Some examples of information it hods:

    boolean finished = future.isDone(); //Check if the async execution has completed
    future.get(10L, TimeUnit.SECONDS); //Wait for completion with timeout
    future.cancel(true); //cancel the execution
    

    java.lang.Void is a reference type for void (a placeholder that doesn't get instantiated). So you can look at Future<Void> the same way you look at Future<Object>, just keeping in mind what you know about void not returning any value.

    You can read more about these types here: