To chain two operations using CompletableFuture
in Java, you can use the thenCompose
or thenComposeAsync
methods. These methods allow you to specify a function that takes the result of the previous operation as input and returns a new CompletableFuture
representing the result of the next operation.
Here is an example of how to chain two operations using thenCompose
:
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { // Perform some computation and return a result return 1; }); CompletableFuture<String> future2 = future1.thenCompose(result -> { // Use the result of the first operation to perform the second operation return CompletableFuture.supplyAsync(() -> { return result + "string"; }); }); // Get the result of the second operation String result = future2.get();
In this example, the first operation is performed asynchronously and returns the result 1
. The second operation is then performed asynchronously, using the result of the first operation as input. The thenCompose
method returns a new CompletableFuture
representing the result of the second operation, which can be obtained using the get
method.
You can also use the thenComposeAsync
method to perform the second operation asynchronously, if you want to offload the work to a separate thread pool.