Sobes.tech
Senior

What is CompletableFuture used for?

sobes.tech AI

Answer from AI

CompletableFuture in Java is a class from the java.util.concurrent package that represents a future result of an asynchronous operation.

Main features:

  • Allows executing tasks asynchronously without blocking the main thread.
  • Supports chaining and combining asynchronous operations using methods like thenApply, thenCompose, thenAccept.
  • Enables error handling and task cancellation.

Example of usage:

CompletableFuture.supplyAsync(() -> {
    // Long operation
    return "Result";
}).thenApply(result -> {
    // Process the result
    return result.length();
}).thenAccept(length -> {
    System.out.println("Result length: " + length);
});

CompletableFuture is useful for building complex asynchronous chains and managing them, which improves code readability and performance.