Sobes.tech
Senior

Tell me about Future and CompletableFuture, what is the difference?

sobes.tech AI

Answer from AI

Future is an interface representing the result of an asynchronous operation that may be obtained in the future. It allows checking if the task is completed, canceling it, and retrieving the result using the get() method, which blocks the thread until the result is ready.

CompletableFuture is an extension of Future that implements the CompletionStage interface. It supports reactive chain programming, allowing you to set up sequential and parallel operations that execute after the completion of an asynchronous task without blocking.

Main differences:

  • Future does not support functional operations and composition.
  • CompletableFuture allows creating processing chains, combining multiple asynchronous tasks, and handling exceptions.
  • CompletableFuture can be explicitly completed (complete), which is useful for manual control.

Example of using CompletableFuture:

CompletableFuture.supplyAsync(() -> "Hello")
    .thenApply(s -> s + " World")
    .thenAccept(System.out::println);
Tell me about Future and CompletableFuture, what is… - sobes.tech