CompletableFuture: Processing Results
This lesson discusses, how to process the result of a CompletableFuture.
In the previous lesson, we looked at CompletableFuture
. We discussed how to create a CompletableFuture
object and how to run tasks asynchronously.
In this lesson, we will look at how to process the result of a CompletableFuture
.
Processing the result of CompletableFuture
Suppose we have a CompletableFuture
and we need to process the result of its execution. Now, the get()
method of CompletableFuture
is blocking. This means we need to wait until we get the result of the first task. After getting the result, we can modify the result.
For our system to be truly asynchronous we should be able to attach a callback to the CompletableFuture
, which should be automatically executed when the Future
completes. That way, we won’t need to wait for the result, and we can write the logic that needs to be executed after the completion of the Future
inside our callback function.
There are a few ways in which we can do this. We will look at each of them one by one.
1) thenApply()
The thenApply()
method accepts a Function<T, R>
instance as parameter. As we have discussed earlier, the Function<T, R>
interface takes in a parameter of type T
and returns a result of type R
.
The thenApply()
method uses the Function<T, R>
instance to process the result and returns a Future
that holds a value returned by the function, i.e., CompletableFuture<R>
In the below example, we have a CompletableFuture
that returns an Integer
. Then, we call thenApply()
method to double the result of CompletableFuture
and return the final result.
Get hands-on with 1200+ tech skills courses.