CompletableFuture
About
Java CompletableFuture is a class introduced in Java 8 as part of the java.util.concurrent package that implements the Future and CompletionStage Interface. It represents a future result of an asynchronous computation that might not be available immediately. It acts like a placeholder for the eventual outcome of an operation that's being executed concurrently by different thread. It provides a way to write asynchronous, non-blocking code in Java, especially when dealing with tasks that might take a long time to complete, such as network requests or database queries.
Advantages:
Asynchronous Programming: CompletableFuture enables you to execute long-running task/tasks without blocking the current thread. This allows the application to remain responsive and handle other requests while the asynchronous operations are in progress.
Composable Operations: CompletableFuture provides a vast set of methods to chain together multiple asynchronous operations, forming complex workflows. We can define what happens after a computation finishes successfully (thenApply, thenAccept), what to do if it encounters an exception (exceptionally), and how to combine results from multiple CompletableFutures (allOf, anyOf).
Improved Error Handling: CompletableFuture offers more complex mechanisms for handling exceptions that arise during asynchronous computations. We can define fallback actions using exceptionally and propagate or chain exceptions using methods like handle.
Some Key Points:
supplyAsync
supplyAsync(Supplier<U> supplier, Executor executor): This method initiates an asynchronous task that returns a value of type U. The provided Supplier is executed asynchronously, and the result is wrapped in a CompletableFuture. An optional Executor can be provided to specify the thread pool where the computation will be executed.
runAsync
runAsync(Runnable runnable, Executor executor): Similar to supplyAsync(), but for tasks that do not return a value. The provided Runnable is executed asynchronously, and the resulting CompletableFuture completes when the task finishes.
thenApply
thenApply(Function<? super T,? extends U> fn): This method specifies a function to be applied to the result of the current CompletableFuture when it completes. It returns a new CompletableFuture that holds the result of the function.
thenAccept
thenAccept(Consumer<? super T> action): Similar to thenApply(), but for cases where you want to perform an action (such as printing or logging) on the result without returning a value. It accepts a Consumer that takes the result as input.
thenCombine
thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn): This method combines the result of the current CompletableFuture with the result of another CompletionStage when both are complete. It applies the specified function to the results of both stages and returns a new CompletableFuture holding the combined result.
thenCompose
thenCompose(Function<? super T,? extends CompletionStage<U>> fn): This method applies a function to the result of the current CompletableFuture and returns a new CompletionStage. It's useful for chaining dependent asynchronous tasks where the result of one task determines the execution of another.
exceptionally
exceptionally(Function<Throwable,? extends T> fn): This method handles exceptions that occur during the execution of the current CompletableFuture. It applies the specified function to the exception and returns a new CompletableFuture with the result of the function, effectively recovering from the exception.
exceptionallyAsync
exceptionallyAsync(Function<Throwable, ? extends T> fn): This method is also used for handling exceptions that may occur during the execution of the asynchronous computation. However, it differs from exceptionally in how it handle the execution context (thread) in which the exception handling function is invoked.
handle
handle(BiFunction<? super T,Throwable,? extends U> fn): Similar to exceptionally(), but the function provided can handle both the result and any exception that occurs during the execution of the current CompletableFuture. If an exception occurs during the execution, the handle() function receives the exception object and if no exception occurs, the handle() function receives the result, and we modify it.
allOf
allOf(CompletableFuture<?>... cfs): This method waits for all of the provided CompletableFutures to complete. It returns a new CompletableFuture that completes when all of the provided CompletableFutures are done, regardless of their individual results.
anyOf
anyOf(CompletableFuture<?>... cfs): This method waits for any of the provided CompletableFutures to complete. It returns a new CompletableFuture that completes when any of the provided CompletableFutures completes, with the result of the first completed CompletableFuture.
orTimeout
orTimeout(long timeout, TimeUnit unit):This method sets a timeout for the completion of the future. If the future does not complete within the specified timeout duration, it completes exceptionally with a TimeoutException. It's useful when you want to handle the timeout by throwing an exception. The timeout is set on the original CompletableFuture, and if the timeout occurs, the CompletableFuture itself is completed exceptionally.
completeOnTimeout
completeOnTimeout(T value, long timeout, TimeUnit unit): This method sets a timeout for the completion of the future. If the future does not complete within the specified timeout duration, it completes with the provided value. It's useful when you want to handle the timeout by providing a fallback value instead of throwing an exception. The timeout is set on a new CompletableFuture derived from the original CompletableFuture, and if the timeout occurs, the new CompletableFuture is completed with the specified value, while the original CompletableFuture remains incomplete.
cancel
cancel(boolean mayInterruptIfRunning): This method cancels the computation associated with the current CompletableFuture, if possible.
join
join(): This method waits for the completion of the current CompletableFuture and returns its result, blocking if necessary until the result is available.
get
get(): This method is similar to join() i.e. wait (block) the current thread until the CompletableFuture finishes its execution, but it can throw checked exceptions. It waits for the completion of the current CompletableFuture and returns its result, but it also throws any exception that occurred during the computation, wrapped in a ExecutionException.
Example:
Creating a single CompletableFuture using
supplyAsync.

Multiple asynchronous operations using
supplyAsync.

Creating a single CompletableFuture using
runAsync.

Example using
thenApply.

Example using
thenAccept.
Example using
thenCombine.
Example using
thenCompose.
Example using
orTimeoutandexceptionallyAsync

Example using
exceptionally.

Example using
orTimeout.

Example using
completeOnTimeout.
Example using
handle.

Example using
allOf.
Example using
anyOf.
Example using
cancel.

Example using
getandjoin.

Use Cases:
When we have a list of account IDs and want to fetch the balance with the help of those IDs by calling external API parallelly.

Last updated