How to use CompletableFuture in Java?

By | March 6, 2023

CompletableFuture is a class in Java that allows you to write asynchronous, non-blocking code using a fluent API. Here are the steps to use CompletableFuture in Java:

  1. Create a CompletableFuture object:

CompletableFuture<Integer> completableFuture = new CompletableFuture<>();

  1. Supply a function that will be executed asynchronously to the CompletableFuture object. The function can be supplied using the supplyAsync method:

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {

    // Perform some expensive computation

    return 42;

});

  1. Chain multiple functions together using the thenApply method. The thenApply method takes a Function as an argument, and returns a new CompletableFuture object:

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {

    // Perform some expensive computation

    return 42;

}).thenApply(result -> {

    // Process the result of the expensive computation

    return result * 2;

});

  1. You can also chain multiple functions together using the thenCompose method. The thenCompose method takes a Function that returns a CompletableFuture as an argument:

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {

    // Perform some expensive computation

    return 42;

}).thenCompose(result -> CompletableFuture.supplyAsync(() -> {

    // Perform another expensive computation using the result of the first computation

    return result * 2;

}));

  1. Use the join method to block the current thread and wait for the CompletableFuture to complete:

int result = completableFuture.join();

Alternatively, you can use the get method, which throws a checked exception if the CompletableFuture completes exceptionally:

int result = completableFuture.get();

  1. Handle exceptions using the exceptionally method. The exceptionally method takes a Function that handles the exception and returns a default value:

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {

    // Perform some expensive computation

    throw new RuntimeException(“Something went wrong”);

}).exceptionally(ex -> {

    // Handle the exception and return a default value

    return -1;

});

That’s it! You can use these basic steps to write complex asynchronous code using CompletableFuture in Java.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *