A CompletableFuture in Java is a class in the java.util.concurrent package that represents a future (an abstract representation of a value that may be available at some point in time after an asynchronous computation is completed). It is designed to ease asynchronous programming by providing methods to perform non-blocking, asynchronous tasks and combine them in various ways.
CompletableFuture was introduced in Java 8, and it significantly enhances Future<T> (an older interface) by allowing chaining, composition, and callbacks, making your code easier to write and reason about.
Key Features of CompletableFuture
-
Asynchronous Programming:
- Allows you to execute tasks asynchronously without blocking the main thread.
- You can run tasks on different threads, letting your program continue doing other work while those tasks complete.
-
Non-blocking Calls:
- You don't have to
wait() or block() for a result.
- Instead, you can specify what should happen once the result becomes available using callback methods like
.thenApply(), .thenAccept(), or .thenRun().
-
Compose/Combine Futures:
- You can chain multiple
CompletableFuture objects together to express complex asynchronous workflows (e.g., run task B once task A finishes).
- You can combine results from different asynchronous tasks into one.
-
Manual Completion:
- A
CompletableFuture can be manually completed by calling methods like .complete() or .completeExceptionally(), which gives developers control over its lifecycle.
How Does CompletableFuture Work?
- A
CompletableFuture starts off "empty" and represents a computation that hasn't completed yet.
- At some point, a result is either:
- Manually completed (using
.complete(...)), or
- Fullfilled by an asynchronous computation.
- Once completed, other dependent computations (chained callbacks) can automatically trigger using methods like
.thenApply() or .thenAccept().
Example: A Simple CompletableFuture
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
// Create a CompletableFuture to simulate a background task
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Simulate a task or network call
sleep(2000); // Simulate 2 seconds of work
return "Hello, World!";
});
// Define a callback to process the result once it's available
future.thenAccept(result -> {
System.out.println("Result: " + result); // Will print the result when future completes
});
System.out.println("Main thread is free to do other things...");
sleep(3000); // Sleep to ensure async task finishes before program ends
}
private static void sleep(long millis) {
try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
Explanation:
CompletableFuture.supplyAsync() runs a task asynchronously on a default thread pool.
- When the asynchronous task finishes, the callback provided via
.thenAccept() processes the result and prints it.
- The main thread is free to perform other actions while waiting for the result.
Key Methods in CompletableFuture
Here’s a breakdown of the important methods:
Creation Methods
supplyAsync(Supplier<T>): Runs a task asynchronously and provides a result.
runAsync(Runnable): Runs a task asynchronously but doesn't provide a result (void return).
complete(T value): Manually completes the CompletableFuture with the given value.
When the Future Completes
thenApply(Function<T, R>): Transforms the completion result into another value.
thenAccept(Consumer<T>): Accepts the result and performs some action (no return value).
thenRun(Runnable): Runs a callback once the future is complete (no result is passed).
Combining Multiple Futures
allOf(CompletableFuture...): Creates a new CompletableFuture that completes when all provided futures are complete.
anyOf(CompletableFuture...): Creates a new CompletableFuture that completes when any one of the provided futures is complete.
Exception Handling
exceptionally(Function<Throwable, T>): Handles exceptions and allows you to recover or provide a fallback result.
handle(BiFunction<T, Throwable, U>): Acts as a catch-all for results and exceptions.
What Makes CompletableFuture Different from Future?
Prior to Java 8, we used the Future<T> interface for asynchronous programming. However, Future is limited and inconvenient:
- You had to block to get the result (
future.get()).
- There were no "chaining" or "composition" capabilities with
Future.
CompletableFuture solves these issues:
- You can work with results asynchronously without blocking (via callbacks).
- You can easily chain or combine multiple asynchronous tasks.
- You can handle errors or results uniformly.
Example Use Case: Aggregating Results from Multiple Futures
import java.util.concurrent.CompletableFuture;
import java.util.List;
public class CompletableFutureExample {
public static void main(String[] args) {
// Simulate multiple asynchronous tasks
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> "Task 1");
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> "Task 2");
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> "Task 3");
// Aggregate results into a list
CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2, task3);
// When all tasks complete, process their results
CompletableFuture<List<String>> result = allTasks.thenApply(v -> List.of(
task1.join(), task2.join(), task3.join()
));
// Print the aggregated result
result.thenAccept(res -> System.out.println("Aggregated Result: " + res));
}
}
Output:
Aggregated Result: [Task 1, Task 2, Task 3]
This shows how you can wait for multiple asynchronous tasks, collect their results, and process them in a non-blocking way.
Summary
CompletableFuture is a powerful tool for:
- Writing clean, non-blocking, asynchronous code in Java.
- Chaining and combining multiple asynchronous tasks.
- Handling exceptions and complex workflows in a readable manner.
Let me know if you'd like further details or examples!