1. Introduction
In the CompletableFuture framework, thenApply() and thenApplyAsync() are crucial methods that facilitate asynchronous programming.
In this tutorial, we’ll delve into the differences between thenApply() and thenApplyAsync() in CompletableFuture. We’ll explore their functionalities, use cases, and when to choose one over the other.
2. Understanding thenApply() and thenApplyAsync()
CompletableFuture provides the methods thenApply() and thenApplyAsync() for applying transformations to the result of a computation. Both methods enable chaining operations to be performed on the result of a CompletableFuture.
2.1. thenApply()
thenApply() is a method used to apply a function to the result of a CompletableFuture when it completes. It accepts a Function functional interface, applies the function to the result, and returns a new CompletableFuture with the transformed result.
2.2. thenApplyAsync()
thenApplyAsync() is a method that executes the provided function asynchronously. It accepts a Function functional interface and an optional Executor and returns a new CompletableFuture with the asynchronously transformed result.
3. Execution Thread
The primary difference between thenApply() and thenApplyAsync() lies in their execution behavior.
3.1. thenApply()
By default, thenApply() method executes the transformation function using the same thread that completed the current CompletableFuture. This means that the execution of the transformation function may occur immediately after the result becomes available. This can potentially block the thread if the transformation function is long-running or resource-intensive.
However, if we call thenApply() on a CompletableFuture that hasn’t yet completed, it executes the transformation function asynchronously in another thread from the executor pool.
Here’s a code snippet illustrating thenApply():
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> thenApplyResultFuture = future.thenApply(num -> "Result: " + num);
String thenApplyResult = thenApplyResultFuture.join();
assertEquals("Result: 5", thenApplyResult);
In this example, if the result is already available and the current thread is compatible, thenApply() might execute the function synchronously. However, it’s important to note that CompletableFuture intelligently decides whether to execute synchronously or asynchronously based on various factors, such as the availability of the result and the threading context.
3.2. thenApplyAsync()
In contrast, thenApplyAsync() guarantees asynchronous execution of the provided function by utilizing a thread from an executor pool, typically the ForkJoinPool.commonPool(). This ensures that the function is executed asynchronously and may run in a separate thread, preventing any blocking of the current thread.
Here’s how we can use thenApplyAsync():
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num);
String thenApplyAsyncResult = thenApplyAsyncResultFuture.join();
assertEquals("Result: 5", thenApplyAsyncResult);
In this example, even if the result is immediately available, thenApplyAsync() always schedules the function for asynchronous execution on a separate thread.
4. Control Thread
While both thenApply() and thenApplyAsync() enable asynchronous transformations, they differ in their support for specifying custom executors and thus controlling the execution thread.
4.1. thenApply()
The thenApply() method doesn’t directly support specifying a custom executor to control the execution thread. It relies on the default behavior of CompletableFuture, which may execute the transformation function on the same thread that completed the previous stage, typically a thread from the common pool.
4.2. thenApplyAsync()
In contrast, thenApplyAsync() allows us to explicitly specify an executor to control the execution thread. By providing a custom executor, we can dictate where the transformation function executes, enabling more precise thread management.
Here’s how we can use a custom executor with thenApplyAsync():
ExecutorService customExecutor = Executors.newFixedThreadPool(4);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 5;
}, customExecutor);
CompletableFuture<String> resultFuture = future.thenApplyAsync(num -> "Result: " + num, customExecutor);
String result = resultFuture.join();
assertEquals("Result: 5", result);
customExecutor.shutdown();
In this example, a custom executor with a fixed thread pool size of 4 is created. The thenApplyAsync() method then uses this custom executor, providing control over the execution thread for the transformation function.
5. Exception Handling
The key difference in exception handling between thenApply() and thenApplyAsync() lies in when and how the exception becomes visible.
5.1. thenApply()
If the transformation function provided to thenApply() throws an exception, the thenApply() stage immediately completes the CompletableFuture exceptionally. This exceptional completion carries the thrown exception within a CompletionException, wrapping the original exception.
Let’s illustrate this with an example:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
assertThrows(CompletionException.class, () -> resultFuture.join());
In this example, we’re trying to divide 5 by 0, which results in an ArithmeticException being thrown. This CompletionException is directly propagated to the next stage or the caller, meaning any exception within the function is immediately visible for handling. So, if we try to access the result using methods like get(), join(), or thenAccept(), we encounter CompletionException directly:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
try {
// Accessing the result using join()
String result = resultFuture.join();
assertEquals("Result: 5", result);
} catch (CompletionException e) {
assertEquals("java.lang.ArithmeticException: / by zero", e.getMessage());
}
In this example, the exception thrown during the function passed to thenApply(). The stage recognizes the problem and wraps the original exception in a CompletionException, allowing us to handle it further down the line.
5.2. thenApplyAsync()
While the transformation function runs asynchronously, any exception within it isn’t directly propagated to the returned CompletableFuture. The exception isn’t immediately visible when we call methods like get(), join(), or thenAccept(). These methods block until the asynchronous operation finishes, potentially leading to deadlock if not handled correctly.
To handle exceptions in thenApplyAsync(), we must use dedicated methods like handle(), exceptionally(), or whenComplete(). These methods allow us to intercept and process the exception when it occurs asynchronously.
Here is the code snippet to demonstrate explicit handling with handle:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num / 0);
String result = thenApplyAsyncResultFuture.handle((res, error) -> {
if (error != null) {
// Handle the error appropriately, e.g., return a default value
return "Error occurred";
} else {
return res;
}
})
.join(); // Now join() won't throw the exception
assertEquals("Error occurred", result);
In this example, even though an exception occurred within thenApplyAsync(), it isn’t directly visible in the resultFuture. The join() method blocks and eventually unwraps the CompletionException, revealing the original ArithmeticException.
6. Use Case
In this section, we’ll explore common use cases for thenApply() and thenApplyAsync() methods in CompletableFuture.
6.1. thenApply()
The thenApply() method is particularly useful in the following scenarios:
- Sequential Transformation: When there is a need to sequentially apply a transformation to the result of a CompletableFuture. This could involve tasks such as converting a numeric result to a string or performing calculations based on the result.
- Lightweight Operations: It’s well-suited for executing small, quick transformations that won’t impose significant blocking on the calling thread. Examples include converting numbers to strings, performing calculations based on the result, or manipulating data structures.
6.2. thenApplyAsync()
On the other hand, the thenApplyAsync() method is appropriate in the following situations:
- Asynchronous Transformation: When there’s a requirement to apply a transformation asynchronously, possibly leveraging multiple threads for parallel execution. For instance, in a web application where users upload images for editing, employing asynchronous transformation with CompletableFuture can be beneficial for concurrently applying resizing, filters, and watermarks, thus enhancing processing efficiency and user experience.
- Blocking Operations: In cases where the transformation function involves blocking operations, I/O operations, or computationally intensive tasks, thenApplyAsync() becomes advantageous. By offloading such computations to a separate thread, helps prevent blocking the calling thread, thereby ensuring smoother application performance.
7. Summary
Here’s a summary table comparing the key differences between thenApply() and thenApplyAsync().
Feature | thenApply() | thenApplyAsync() |
---|---|---|
Execution Behavior | Same thread as the previous stage or a separate thread from the executor pool (if called before completion) | Separate thread from executor pool |
Custom Executor Support | Not supported | Supports custom executor for thread control |
Exception Handling | Immediately propagates exception within CompletionException | Exception not directly visible requires explicit handling |
Performance | May block calling thread | Avoids blocking and enhances performance |
Use Cases | Sequential transformations, lightweight operations | Asynchronous transformations, blocking operations |
8. Conclusion
In this article, we’ve explored the functionalities and differences between the thenApply() and thenApplyAsync() methods in the CompletableFuture framework.
thenApply() may potentially block the thread, making it suitable for lightweight transformations or scenarios where synchronous execution is acceptable. On the other hand, thenApplyAsync() guarantees asynchronous execution, making it ideal for operations involving potential blocking or computationally intensive tasks where responsiveness is critical.
As always, the source code for the examples is available over on GitHub.