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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – 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 – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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

Having high performance and availability are essential parts of modern software development.

One way to achieve this is through non-blocking and asynchronous programming. In Java, the CompletableFuture class provides a way to write non-blocking code. But is it truly non-blocking?

In this tutorial, we’ll examine the situations when CompletableFuture is blocking and when it is non-blocking.

2. CompletableFuture

Firstly, let’s take a brief look at CompletableFuture class. It’s a powerful class introduced in Java 8 as part of the Concurrent API.

Moreover, it implements the Future interface and represents the primary implementation of the CompletionStage interface. Thus, it offers nearly 50 different methods for creating and executing asynchronous computations.

Why did we need CompletableFurure in the first place? Using the Future interface, we could only retrieve the result by calling the get() method. However, this method represents a blocking operation. In other words, it’ll block the current thread until the result of the task becomes available.

If we need to perform additional actions on the result, we’ll end up with blocking operations.

On the other hand, thanks to CompletionStage, CompletableFuture provides the ability to chain multiple computations together that can run concurrently. This functionality allows us to create a chain of tasks where the next task is triggered when the current task is completed.

Furthermore, we can specify what should happen once we get the result from the future without blocking the current thread.

The CompletableFuture class represents both the stage in dependent processes, where one stage’s completion triggers another, and its result.

3. Blocking vs. Non-blocking

Next, let’s understand the difference between blocking and non-blocking processing.

In the blocking operation, the calling thread waits until the operation in another thread completes before continuing with its execution:

 

blocking processing

Here, the tasks execute sequentially. Thread 1 is blocked by Thread 2. In other words, Thread 1 can’t continue with its execution until Thread 2 finishes processing its tasks.

We can look at the blocking processing as synchronous operations.

However, blocking operations in our system can cause performance issues, especially in applications that require high availability and scalability.

In contrast, a non-blocking operation allows threads to perform multiple computations simultaneously without having to wait for each task to complete.

The current thread can continue with its execution while the other threads perform tasks in parallel:

non-blocking processing

In the example above, Thread 2 isn’t blocking the execution of Thread 1. Furthermore, both threads are running their tasks concurrently.

Besides improving the performance, we can decide what to do with the result once the non-blocking operation finishes with execution.

4. CompletableFuture and Non-blocking Operations

The main advantage of using CompletableFuture is its ability to chain multiple tasks together that will be executed without blocking the current thread. Therefore, we can say the CompletableFuture is non-blocking.

Additionally, it provides several methods that allow us to perform tasks in a non-blocking way, including:

  • supplyAsync(): executes a task asynchronously and returns a CompletableFuture representing the result
  • thenApply(): applies a function to the result of a previous task and returns a CompletableFuture representing the transformed result
  • thenCompose(): executes a task that returns a CompletableFuture and returns a CompletableFuture representing the result of the nested task
  • allOf(): executes several tasks in parallel and returns a CompletableFuture representing the completion of all tasks

Next, let’s see a simple example. For instance, suppose we have two tasks we’d like to execute as non-blocking:

CompletableFuture.supplyAsync(() -> "Baeldung")
  .thenApply(String::length)
  .thenAccept(s -> logger.info(String.valueOf(s)));

After the task completes, it’ll print the number 8 on the standard output.

The computation runs in the background and returns a future. If we have multiple dependent actions, each action is represented by the stage. After one stage completes, it triggers the computation of other dependent stages.

5. When Is CompletableFuture Blocking?

Although CompletableFuture is used to perform non-blocking operations, it can still end up blocking the current thread in certain scenarios.

In asynchronous communication, we usually have a callback mechanism to retrieve the result of the computation. However, CompletableFuture doesn’t notify us upon its completion.

If needed, we can retrieve the result in the calling thread using the get() method.

Nevertheless, we need to be aware the get() method returns the result using blocking processing. If required, it waits for the computation to complete and then returns the result.

Therefore, we’ll end up blocking the current thread until the future completes:

CompletableFuture<String> completableFuture = CompletableFuture
  .supplyAsync(() -> "Baeldung")
  .thenApply(String::toUpperCase);

assertEquals("BAELDUNG", completableFuture.get());

Similarly, calling the join() method will block the current thread as well:

CompletableFuture<String> completableFuture = CompletableFuture
  .supplyAsync(() -> "Blocking")
  .thenApply(s -> s + " Operation")
  .thenApply(String::toLowerCase);

assertEquals("blocking operation", completableFuture.join());

The main difference between these two methods is that the join() method doesn’t throw checked exceptions if the future completes exceptionally.

Additionally, we can call the isDone() method to check whether the future is completed before obtaining the result.

However, when it’s necessary to obtain the computation result in the calling thread, we can create CompletableFuture, do other work in the current thread, and then call the get() or join() method. By giving it more time, it’s more likely the Future will finish with computations before we get the result. But there’s still no guarantee that the retrieval won’t end up blocking the thread.

6. Conclusion

In this article, we examined the scenarios when CompletableFuture is non-blocking and when it’s not.

To sum up, CompletableFuture is non-blocking most of the time. However, if we call the get() or the join() methods to retrieve the result, they will block the current thread.

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.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

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)