Java CompletableFuture: A Deep Dive šŸŽÆ

beginner
23 min

Java CompletableFuture: A Deep Dive šŸŽÆ

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! 🐳

Understanding CompletableFuture šŸ’”

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.

java
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> { // Asynchronous task code here });

šŸ“ Note: CompletableFuture can be used for both computation and I/O operations.

Creating and Managing CompletableFutures šŸ’”

We can create a CompletableFuture in three ways:

  1. CompletableFuture.supplyAsync(): returns a new CompletableFuture representing the result of an asynchronous computation.
  2. CompletableFuture.runAsync(): runs an asynchronous task that may throw an exception.
  3. CompletableFuture.completedFuture(): returns a CompletableFuture that completes with a given value or an exception.

Examples šŸ’”

Example 1: Simple Computation

java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { // Perform a computation Thread.sleep(2000); // Simulate a long computation return 42; }); // Continue with other code

Example 2: Reading a File

java
Path 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 code

Combining CompletableFutures šŸ’”

We can combine multiple CompletableFutures using methods like thenApply(), thenAccept(), thenRun(), and thenCombine(). These methods are called when the initial CompletableFuture completes.

Example šŸ’”

java
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 1); CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 2); CompletableFuture.allOf(future1, future2) .thenApply((ignored) -> future1.join() + future2.join());

Exceptions and Error Handling šŸ’”

Exceptions in CompletableFuture are handled using methods like exceptionally() and handle().

Example šŸ’”

java
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Oops!"); }); future.exceptionally((ex) -> { System.err.println("Error occurred: " + ex.getMessage()); return 0; });

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is CompletableFuture in Java?

Quick Quiz
Question 1 of 1

How can we create a CompletableFuture in Java?