Welcome to your comprehensive guide on Java's CompletableFuture! In this lesson, we'll explore this powerful tool that simplifies asynchronous programming and improves efficiency. Let's dive right in! š³
CompletableFuture is a utility class in Java 8 and later versions that represents the result of an asynchronous computation. It's a promise of a supply of a result, either a value or an exception.
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> {
// Asynchronous task code here
});š Note: CompletableFuture can be used for both computation and I/O operations.
We can create a CompletableFuture in three ways:
CompletableFuture.supplyAsync(): returns a new CompletableFuture representing the result of an asynchronous computation.CompletableFuture.runAsync(): runs an asynchronous task that may throw an exception.CompletableFuture.completedFuture(): returns a CompletableFuture that completes with a given value or an exception.CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
// Perform a computation
Thread.sleep(2000); // Simulate a long computation
return 42;
});
// Continue with other codePath path = Paths.get("example.txt");
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try (BufferedReader reader = Files.newBufferedReader(path)) {
return reader.lines().reduce("", String::concat);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
// Continue with other codeWe can combine multiple CompletableFutures using methods like thenApply(), thenAccept(), thenRun(), and thenCombine(). These methods are called when the initial CompletableFuture completes.
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture.allOf(future1, future2)
.thenApply((ignored) -> future1.join() + future2.join());Exceptions in CompletableFuture are handled using methods like exceptionally() and handle().
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Oops!");
});
future.exceptionally((ex) -> {
System.err.println("Error occurred: " + ex.getMessage());
return 0;
});What is CompletableFuture in Java?
How can we create a CompletableFuture in Java?