eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

eBook – Java Concurrency – NPI (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook – Java Concurrency – NPI (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments