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

1. Introduction

When creating software capabilities, an everyday activity is retrieving data from different sources and aggregating it in the response. In microservices, those sources are often external REST APIs.

In this tutorial, we’ll use Java’s CompletableFuture to efficiently retrieve data from multiple external REST APIs in parallel.

2. Why Use Parallelism in REST Calls

Let’s imagine a scenario where we need to update various fields in an object, each field value coming from an external REST call. One alternative is to call each API sequentially to update each field.

However, waiting for one REST call to complete to start another increases our service’s response time. For instance, if we call two APIs that take 5 seconds each, the total time would be at least 10 seconds since the second call needs to wait for the first to complete.

Instead, we can call all APIs in parallel so that the total time would be the time of the slowest REST call. For example, one call takes 7 seconds, and another 5 seconds. In that case, we’ll wait 7 seconds since we have processed everything in parallel and must wait for all the results to complete.

Hence, parallelism is an excellent alternative to reduce our services’ response times, making them more scalable and improving user experience.

3. Using CompletableFuture for Parallelism

The CompletableFuture class in Java is a handy tool for combining and running different parallel tasks and handling individual task errors.

In the following sections, we’ll use it to combine and run three REST calls for each object in an input list.

3.1. Creating the Demo Application

Let’s first define our target POJO for updates:

public class Purchase {
    String orderDescription;
    String paymentDescription;
    String buyerName;
    String orderId;
    String paymentId;
    String userId;

    // all-arg constructor, getters and setters
}

The Purchase class has three fields that should be updated, each one by a different REST call queried by an ID.

Let’s first create a class that defines a RestTemplate bean and a domain URL for the REST calls:

@Component
public class PurchaseRestCallsAsyncExecutor {
    RestTemplate restTemplate;
    static final String BASE_URL = "https://internal-api.com";

    // all-arg constructor
}

Now, let’s define the /orders API call:

public String getOrderDescription(String orderId) {
    ResponseEntity<String> result = restTemplate.getForEntity(String.format("%s/orders/%s", BASE_URL, orderId),
        String.class);

    return result.getBody();
}

Then, let’s define the /payments API call:

public String getPaymentDescription(String paymentId) {
    ResponseEntity<String> result = restTemplate.getForEntity(String.format("%s/payments/%s", BASE_URL, paymentId),
        String.class);

    return result.getBody();
}

And finally, we define the /users API call:

public String getUserName(String userId) {
    ResponseEntity<String> result = restTemplate.getForEntity(String.format("%s/users/%s", BASE_URL, userId),
        String.class);

    return result.getBody();
}

All three methods use the getForEntity() method to make the REST call and wrap the result in a ResponseEntity object.

Then, we call getBody() to get the response body from the REST call.

3.2. Making Multiple REST Calls With CompletableFuture

Now, let’s create the method that builds and runs a set of three CompletableFutures:

public void updatePurchase(Purchase purchase) {
    CompletableFuture.allOf(
      CompletableFuture.supplyAsync(() -> getOrderDescription(purchase.getOrderId()))
        .thenAccept(purchase::setOrderDescription),
      CompletableFuture.supplyAsync(() -> getPaymentDescription(purchase.getPaymentId()))
        .thenAccept(purchase::setPaymentDescription),
      CompletableFuture.supplyAsync(() -> getUserName(purchase.getUserId()))
        .thenAccept(purchase::setBuyerName)
    ).join();
}

We used the allOf() method to build the steps of our CompletableFuture. Each argument is a parallel task in the form of another CompletableFuture built with the REST call and its result.

To build each parallel task, we first used the supplyAsync() method to provide the Supplier from which we’ll retrieve our data. Then, we use thenAccept() to consume the result from supplyAsync() and set it on the corresponding field in the Purchase class.

At the end of allOf(), we’ve just built the tasks up to there. No action was taken.

Finally, we call join() at the end to run all tasks in parallel and collect their results. Since join() is a thread-blocking operation, we only call it at the end instead of at each task step. This is to optimize the application performance by having fewer thread blocks.

Since we didn’t provide a customized ExecutorService to the supplyAsync() method, all tasks run in the same executor. By default, Java uses ForkJoinPool.commonPool().

In general, it’s a good practice to specify a custom ExecutorService to supplyAsync() so we will have more control over our thread pool parameters.

3.3. Executing Multiple REST Calls for Each Element in a List

To apply our updatePurchase() method on a collection, we can simply call it in a forEach() loop:

public void updatePurchases(List<Purchase> purchases) {
    purchases.forEach(this::updatePurchase);
}

Our updatePurchases() method receives a list of Purchases and applies the previously created updatePurchase() method to each element.

Each call to updatePurchases() runs three parallel tasks as defined in our CompletableFuture. Hence, each purchase has its own CompletableFuture object to run the three parallel REST calls.

4. Handling Errors

In distributed systems, it’s pretty common to have service unavailability or network failures. Those failures might happen in external REST APIs that we, as the clients of that API, are unaware of. For instance, if the application is down, the request sent over the wire never completes.

4.1. Handling Errors Gracefully Using handle()

Exceptions may occur during the REST call execution. For instance, if the API service is down or if we input invalid parameters, we’ll get errors.

Hence, we can handle each REST call exception individually using the handle() method:

public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn)

The method argument is a BiFunction containing the result and the exception from the previous task as arguments.

To illustrate, let’s add the handle() step into one of our CompletableFuture‘s steps:

public void updatePurchaseHandlingExceptions(Purchase purchase) {
    CompletableFuture.allOf(
        CompletableFuture.supplyAsync(() -> getPaymentDescription(purchase.getPaymentId()))
          .thenAccept(purchase::setPaymentDescription)
          .handle((result, exception) -> {
              if (exception != null) {
                  // handle exception
                  return null;
              }
              return result;
          })
    ).join();
}

In the example, handle() gets a Void type from setPaymentDescription() called by thenAccept().

Then, it stores in exception any error thrown inside the thenAccept() actions. Hence, we used it to check for an error and handle it properly in the if statement.

Finally, handle() returns the value passed as an argument if no exception was thrown. Otherwise, it returns null.

4.2. Handling REST Call Timeouts

When we work with CompletableFuture, we can specify a task timeout similar to the one we define in our REST calls. Hence, if a task isn’t completed in the specified time, Java finishes the task execution with a TimeoutException.

To do that, let’s modify one of our CompletableFuture’s tasks to handle timeouts:

public void updatePurchaseHandlingExceptions(Purchase purchase) {
    CompletableFuture.allOf(
        CompletableFuture.supplyAsync(() -> getOrderDescription(purchase.getOrderId()))
          .thenAccept(purchase::setOrderDescription)
          .orTimeout(5, TimeUnit.SECONDS)
          .handle((result, exception) -> {
              if (exception instanceof TimeoutException) {
                  // handle exception
                  return null;
              }
              return result;
          })
    ).join();
}

We’ve added the orTimeout() line to our CompletableFuture builder to stop the task execution abruptly if it doesn’t complete in 5 seconds.

We’ve also added an if statement in the handle() method to handle TimeoutException separately.

Adding timeouts to CompletableFuture guarantees that the task always finishes. This is important to avoid a thread hanging indefinitely, waiting for the result of an operation that may never finish. Therefore, it decreases the number of threads in a long-time RUNNING state and increases the application’s health.

5. Conclusion

A common task when working with distributed systems is to make REST calls to different APIs to build a proper response.

In this article, we’ve seen how to use CompletableFuture to build a set of parallel REST call tasks for every object in a collection.

We’ve also seen how to handle timeouts and general exceptions gracefully using the handle() method.

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.

Course – LS – NPI (cat=REST)
announcement - icon

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

>> CHECK OUT THE COURSE

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