CompletableFuture
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.
The executor
parameter is an optional Executor
that specifies where the async computation will be executed. If provided, the async computation will be executed on the specified Executor
. If not provided, the async computation will be executed on the default ForkJoinPool.commonPool()
Specifying an Executor
allows to control the execution context of the async computation. We can use a custom Executor
to control factors such as the number of threads, thread priority, or even to execute tasks on a specific thread, providing more control over concurrency and resource utilization in the application.
Example:
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.
What it Does is it -
Waits for Completion:
thenCompose
waits for the currentCompletableFuture
to complete.Applies Function: Once the current
CompletableFuture
finishes,thenCompose
applies the provided function (fn
) to its result (of typeT
).Chains Another Operation: The function (
fn
) is expected to return a newCompletionStage<U>
. This creates a new asynchronous operation that will be executed after the current one finishes.Returns New CompletableFuture:
thenCompose
returns a newCompletableFuture<U>
that represents the result of the chained operation.
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.
exceptionally(Function<Throwable, ? extends T> fn)
:
This method is synchronous, meaning the provided exception handling function (
Function
) is executed in the same thread where the exception occurred.It's suitable for simple exception handling scenarios where the recovery logic is not computationally intensive and does not involve blocking operations.
The computation of the fallback value happens synchronously, potentially blocking the thread until the recovery logic completes.
exceptionallyAsync(Function<Throwable, ? extends T> fn)
:
This method is asynchronous, meaning the provided exception handling function (
Function
) is executed in a separate thread from the one where the exception occurred.It's suitable for complex exception handling scenarios where the recovery logic might involve heavy computation or blocking operations.
The computation of the fallback value happens asynchronously, allowing the main program to continue executing other tasks while the recovery logic runs concurrently.
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
.
get vs join ?
Exception Handling:
get()
: Throws two types of checked exceptions:ExecutionException
: If the asynchronous computation running within theCompletableFuture
throws an exception.InterruptedException
: If the current thread is interrupted while waiting for theCompletableFuture
to complete.
join()
: Throws a single unchecked exception:CompletionException
: Wraps the original exception that occurred during the asynchronous computation.
Usability in Streams:
get()
: Cannot be used directly within streams due to the checked exceptions it throws. Additional exception handling is required.join()
: Can be used within streams using method references because it throws an unchecked exception. This makes it more convenient for concise stream operations.
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
orTimeout
andexceptionallyAsync
Example using
exceptionally
.
Example using
orTimeout
.
Example using
completeOnTimeout
.
Example using
handle
.
Example using
allOf
.
Example using
anyOf
.
Example using
cancel
.
Example using
get
andjoin
.
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