What is the use case of CompletableFuture in Java?

Candy 43 Published: 10/11/2024

What is the use case of CompletableFuture in Java?

The CompletableFuture class in Java is a part of the Java 8 Concurrency API and is used to handle asynchronous computations that involve callbacks. It provides a way to write asynchronous code that is both readable and maintainable.

Here are some use cases for CompletableFuture:

Handling Callbacks: In traditional callback-based programming, you would pass a callback function to a method, which the method would then invoke when the computation was complete. This can lead to a tangled mess of callbacks and code that is difficult to read. CompletableFuture allows you to handle callbacks in a more readable way by providing a series of methods (e.g., thenApply, thenAccept, etc.) that allow you to specify what should happen when the computation is complete.

Asynchronous Programming: CompletableFuture provides a way to write asynchronous code using lambda expressions or method references, which makes the code more concise and easier to read. Handling Exceptions: When writing asynchronous code, it's important to handle exceptions properly. CompletableFuture provides several methods (e.g., whenComplete, handle, etc.) that allow you to specify what should happen when an exception is thrown during the computation. Composing Computations: CompletableFuture allows you to compose computations by chaining multiple thenApply or thenAccept calls together. This makes it easy to perform complex asynchronous computations in a readable way. Creating Custom Futures: You can also use CompletableFuture to create custom futures that perform specific computations or transformations on the data returned by the computation.

Here's an example of using CompletableFuture to compute the sum of two numbers asynchronously:

import java.util.concurrent.CompletableFuture;

public class Main {

public static void main(String[] args) throws InterruptedException {

int num1 = 10;

int num2 = 20;

CompletableFuture future = CompletableFuture.supplyAsync(() -> {

// simulate some computation

Thread.sleep(1000);

return num1 + num2;

});

try {

int result = future.get(); // block until the computation is complete

System.out.println("Result: " + result);

} catch (Exception e) {

System.out.println("An error occurred: " + e.getMessage());

}

}

}

In this example, CompletableFuture is used to compute the sum of two numbers asynchronously. The computation is simulated by sleeping for 1 second, and the result is printed when it's available.

Overall, CompletableFuture provides a powerful way to write asynchronous code in Java that is both readable and maintainable.

Java CompletableFuture allOf

I'm happy to respond in English!

allOf() is a method provided by the CompletableFuture class in Java, which allows you to combine multiple completable futures into one that completes when all of them have completed.

Here's an example:

import java.util.concurrent.CompletableFuture;

import java.util.concurrent.TimeUnit;

public class CompletableFutureAllOfExample {

public static void main(String[] args) throws InterruptedException {

// Create three completable futures

CompletableFuture future1 = CompletableFuture.completedFuture("Future 1").thenApply(str -> str.toUpperCase());

CompletableFuture future2 = CompletableFuture.completedFuture("Future 2").thenApply(str -> str.toLowerCase());

CompletableFuture future3 = CompletableFuture.runAsync(() -> {

try {

TimeUnit.SECONDS.sleep(2);

return 42;

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

});

// Use allOf() to combine the futures

CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3);

// Wait for the combined future to complete

combinedFuture.get();

}

}

In this example, we create three completable futures: future1, future2, and future3. The first two are simple futures that return strings in uppercase and lowercase respectively. The third one simulates some long-running operation by sleeping for 2 seconds.

We then use the allOf() method to combine these futures into a single future, combinedFuture. This future completes when all three of the original futures have completed.

Finally, we wait for the combined future to complete using the get() method. When this happens, we know that all three of our original futures have completed.

The benefits of allOf() are:

Simplified error handling: When multiple futures are combined with allOf(), a single exception is propagated if any of the futures fail, making it easier to handle errors. Improved code readability: By combining multiple futures into one, you can write more concise and readable code that's easier to maintain. Faster code execution: When multiple futures are combined with allOf(), they can be executed concurrently, which can improve the overall performance of your code.

In summary, allOf() is a powerful method in Java that allows you to combine multiple completable futures into one, making it easier to write concurrent and asynchronous code.