What is CompletableFuture in Java: Simple Explanation and Example
CompletableFuture in Java is a class that helps run tasks asynchronously, meaning tasks can run in the background without stopping the main program. It allows you to write code that waits for these tasks to finish and then continues, making your program faster and more responsive.How It Works
Imagine you are cooking dinner and waiting for water to boil. Instead of just standing there doing nothing, you start chopping vegetables while the water heats up. CompletableFuture works similarly by letting your program start a task and then move on to other work without waiting for the first task to finish.
When the task is done, CompletableFuture lets you handle the result or start another task. This way, your program can do many things at once, improving speed and efficiency.
Example
This example shows how to run a task that waits 2 seconds and then returns a message. The main program continues and prints the message when the task finishes.
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureExample { public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); // Simulate long task } catch (InterruptedException e) { e.printStackTrace(); } return "Task completed!"; }); System.out.println("Waiting for the task..."); // Wait and get the result String result = future.get(); System.out.println(result); } }
When to Use
Use CompletableFuture when you want your program to do multiple things at the same time without waiting for each task to finish before starting the next. This is useful for tasks like fetching data from the internet, reading files, or running calculations that take time.
For example, a web server can handle many user requests simultaneously without making users wait, or a program can load images in the background while showing the user interface.
Key Points
- Asynchronous: Runs tasks in the background without blocking the main program.
- Chaining: You can link tasks to run one after another when the previous finishes.
- Combining: Multiple tasks can be combined to run together or wait for all to finish.
- Error Handling: You can handle errors in asynchronous tasks gracefully.