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.

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

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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

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. Overview

When we’re building a service that depends on other services, we often need to handle cases where a dependent service responds too slowly.

If we use CompletableFuture to manage the calls to our dependencies asynchronously, its timeout capabilities enable us to set a maximum waiting time for the result. If the expected result doesn’t arrive within the specified time, we can take action, such as providing a default value, to prevent our application from getting stuck in a lengthy process.

In this article, we’ll discuss three different ways to manage timeouts in CompletableFuture.

2. Manage Timeout

Imagine an e-commerce app that requires calls to external services for special product offers. We can use CompletableFuture with timeout settings to maintain responsiveness. This can throw errors or provide a default value if a service fails to respond quickly enough.

For example, in this case, let’s say we are going to make a request to an API that returns PRODUCT_OFFERS. Let’s call it fetchProductData(), which we can wrap with a CompletableFuture so we can handle the timeout:

private CompletableFuture<String> fetchProductData() {
    return CompletableFuture.supplyAsync(() -> {
        try {
            URL url = new URL("http://localhost:8080/api/dummy");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                return response.toString();
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            return "";
        }
    });
}

To test timeouts using WireMock, we can easily configure a mock server for timeouts by following the WireMock usage guide. Let’s assume a reasonable web page load time on a typical internet connection is 1000 milliseconds, so we set a DEFAULT_TIMEOUT to that value:

private static final int DEFAULT_TIMEOUT = 1000; // 1 seconds

Then, we’ll create a wireMockServer that gives a body response of PRODUCT_OFFERS and set a delay of 5000 milliseconds or 5 seconds, ensuring that this value exceeds DEFAULT_TIMEOUT to ensure a timeout occurs:

stubFor(get(urlEqualTo("/api/dummy"))
  .willReturn(aResponse()
    .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur.
    .withBody(PRODUCT_OFFERS)));

3. Using completeOnTimeout()

The completeOnTimeout() method resolves the CompletableFuture with a default value if the task doesn’t finish within the specified time.

With this method, we can set the default value <T> to return when a timeout occurs. This method returns the CompletableFuture on which this method is invoked.

In this example, let’s default to DEFAULT_PRODUCT:

CompletableFuture<Integer> productDataFuture = fetchProductData();
productDataFuture.completeOnTimeout(DEFAULT_PRODUCT, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
assertEquals(DEFAULT_PRODUCT, productDataFuture.get());

If we aim for results that remain meaningful even in the event of a failure or timeout during the request, then this approach is appropriate.

In an e-commerce scenario, for instance, when presenting product promotions, if retrieving special promo product data fails or exceeds the timeout, the system displays the default product instead.

4. Using orTimeout()

We can use orTimeout() to augment a CompletableFuture with timeout handling behavior if the future is not completed within a specific time.

This method returns the same CompletableFuture on which this method is applied and will throw a TimeoutException in case of a timeout.

Then, to test this method, we should use assertThrows() to prove an exception was raised:

CompletableFuture<Integer> productDataFuture = fetchProductData();
productDataFuture.orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
assertThrows(ExecutionException.class, productDataFuture::get);

If our priority is responsiveness or time-consuming tasks and we want to provide quick action when a timeout occurs, then this is a suitable approach.

However, proper handling of these exceptions is required for good performance because this method explicitly throws exceptions.

Additionally, the approach is applicable in various scenarios, such as managing network connections, handling IO operations, processing real-time data, and managing queues.

5. Using completeExceptionally()

The CompletableFuture class’s completeExceptionally() method lets us complete the future exceptionally with a specific exception. Subsequent calls to result retrieval methods like get() and join() will throw the specified exception.

This method returns true if the method call resulted in the transition of the CompletableFuture to a completed state. Otherwise, it returns false.

Here, we’ll use ScheduledExecutorService, which is an interface in Java used to schedule and manage task executions at specific times or with delays. It provides flexibility in scheduling recurring tasks, handling timeouts, and managing errors in a concurrent environment:

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
//...
CompletableFuture<Integer> productDataFuture = fetchProductData();
executorService.schedule(() -> productDataFuture.completeExceptionally(
  new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
assertThrows(ExecutionException.class, productDataFuture::get);

If we need to handle TimeoutException along with other exceptions or we want to make it custom or specific, maybe this is a suitable way. We commonly use this approach to handle failed data validation, fatal errors, or when a task does not have a default value.

6. Comparison: completeOnTimeout() vs orTimeout() vs completeExceptionally()

With all these methods, we can manage and control the behavior of CompletableFuture in different scenarios, especially when working with asynchronous operations that require timing and handling timeouts or errors.

Let’s compare the advantages and disadvantages of the completeOnTimeout(), orTimeout(), and completeExceptionally():

Method Advantages Disadvantages
completeOnTimeout() Allowed to replace the default result if a long-running task takes too long

Useful for avoiding timeouts without throwing exceptions  

Doesn’t explicitly mark that a timeout occurred
orTimeout() Generates a TimeoutException explicitly when a timeout occurs

Can handle timeouts in a specific manner

Doesn’t provide an option to replace the default result
completeExceptionally() Allowed to explicitly mark the result with a custom exception

Useful for indicating failure in asynchronous operations

More general purpose than managing timeouts

7. Conclusion

In this article, we’ve looked at three different ways of responding to a timeout in an asynchronous process inside CompletableFuture.

When selecting our approach, we should consider our needs for managing long-running tasks. We should decide between default values, indicating asynchronous operation timeouts with specific exceptions.

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)