What is CompletableFuture in Java?

CompletableFuture is a powerful tool in Java's concurrency framework that allows you to write asynchronous, non-blocking code. It represents a future result of an asynchronous computation, enabling you to handle tasks that complete at some point in the future. CompletableFuture makes it easy to run a task asynchronously and then combine the results of multiple tasks or handle exceptions, all while avoiding callback hell.

Example of CompletableFuture

// Import the necessary packages import java.util.concurrent.CompletableFuture; public class CompletableFutureExample { public static void main(String[] args) { // Create a CompletableFuture that runs a task asynchronously CompletableFuture future = CompletableFuture.supplyAsync(() -> { // Simulate a delay try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello from CompletableFuture!"; }); // Add a callback to handle the result future.thenAccept(result -> { System.out.println(result); }); // Prevent main thread from exiting too soon future.join(); } }

CompletableFuture Java Asynchronous Non-blocking Concurrency