Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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 – 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

Partner – Orkes – NPI EA (cat=Java)
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.

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 – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

While it is common to write unit tests for single-threaded Java, unit tests for concurrent Java are still rarely used.

By using VMLens, an open source tool to deterministically unit test concurrent Java, we can now change this.

In the following tutorial, we’ll learn how to use VMLens to write unit tests for concurrent Java.

2. Setup

As an example, we implement a BankAccount class. We want to update and get the current amount from multiple threads in parallel:

public class RegularFieldBankAccount { private int amount; public void update(int delta) { amount += delta; } // standard getter } 

First of all, we need to add Maven dependencies and plugins to our pom.xml:

<dependency> <groupId>com.vmlens</groupId> <artifactId>api</artifactId> <version>1.2.10</version> <scope>test</scope> </dependency> <plugin> <groupId>com.vmlens</groupId> <artifactId>vmlens-maven-plugin</artifactId> <version>1.2.10</version> <executions> <execution> <id>test</id> <goals> <goal>test</goal> </goals> </execution> </executions> </plugin>

The vmlens-maven-plugin extends the maven-surefire-plugin. So we can configure the VMLens Plugin the same way as the Maven Surefire Plugin. We can find the latest versions of com.vmlens:api and vmlens-maven-plugin:vmlens-maven-plugin in the Maven Central repository.

We can also use VMLens with Gradle or standalone as described here.

3. The Test

To test that we can indeed update the bank account from multiple threads, we let the main and a newly started thread call the update method in parallel. We surround this with a while loop, iterating over all thread interleavings:

@Test public void whenParallelUpdate_thenAmountSumOfBothUpdates() throws InterruptedException { try (AllInterleavings allInterleavings = new AllInterleavings("bankAccount.updateUpdate")) { while (allInterleavings.hasNext()) { RegularFieldBankAccount bankAccount = new RegularFieldBankAccount(); Thread first = new Thread() { @Override public void run() { bankAccount.update(5); } }; first.start(); bankAccount.update(10); first.join(); int amount = bankAccount.getAmount(); assertThat(amount, is(15)); } } } 

The problem with testing concurrent Java is that we need to test all possible execution orders of the threads.

By using the while loop, we instruct VMLens to test all thread interleavings at the specified location in the code.

VMLens runs as a byte-code agent. VMLens traces all synchronization actions and field accesses. Based on this information, VMLens calculates all thread interleavings.

4. Data Races

Running the test leads to the following error, a data race:

Unit test for concurrent Java finds a data race

A data race happens when two threads access the same field simultaneously without proper synchronization. Synchronization actions include operations such as accessing a volatile field or using a synchronized block. We observe from the trace that there are no synchronization actions between the read and write operations to the amount field from different threads.

When a data race happens, there is no guarantee that a reading thread will see the last written value. This is because the compiler reorders instructions, and CPU cores cache field values. Only with synchronization actions in between can we ensure that the thread reads the most recent value.

To write concurrent classes, we need to eliminate data races.

5. Non-atomic Methods

To fix this error, we add a volatile modifier to the field declaration:

public class VolatileFieldBankAccount { private volatile int amount; // Methods same as above } 

Running the test, we get the following error:

Expected: is <15> but: was <10> 

The VMLens trace shows why the amount was not correctly updated:

Unit test for concurrent Java finds a read modify write race condition

The amount += delta operation is not one atomic operation but three independent ones:

  1. reading the value from the field
  2. updating the value
  3. writing back the new value to the field

The trace shows that first the main thread and then Thread-8 read the field. And then first Thread-8 and then the main thread writes to the field. Therefore, the update to Thread-8 gets lost, resulting in the incorrect value.

6. Atomic Methods

The problem is that the update method is not atomic. The read of the amount and the write to the amount should be one indivisible operation.

Therefore, after eliminating data races, we need to make the methods atomic. We can do this by using a synchronized block in the update method:

public class AtomicBankAccount { private final Object LOCK = new Object(); private volatile int amount; public int getAmount() { return amount; } public void update(int delta) { synchronized (LOCK) { amount += delta; } } } 

This class now passes the test.

7. How Are Unit Tests for Concurrent Java Possible?

According to Unit Testing: Principles, Practices, and Patterns by Vladimir Khorikov,

A unit test is an automated test that

  1. Verifies a small piece of code (also known as a unit),
  2. Does it quickly,
  3. And does it in an isolated manner.

The problem with testing concurrent Java is that we need to test all thread interleavings. And that the number of thread interleavings grows exponentially with the number of conflicting synchronization actions. This means that unit tests are a good fit for testing concurrent Java.

Unit tests are fast. This allows for repeated use multiple times. That the unit test verifies only a small piece of code makes it possible to treat the other part of the code as a black box. This reduces the number of thread interleavings that we need to test.

8. What to Test?

We need to test that the methods of our class are atomic. To test this, we need to execute all updating methods in parallel. And all updating and all reading methods in parallel.

The best way is to write a separate test for each combination of updating and reading methods.

So, for our example, we still need a test for the combination of reading and updating:

@Test public void whenParallelUpdateAndGet_thenResultEitherAmountBeforeOrAfterUpdate() throws InterruptedException { try (AllInterleavings allInterleavings = new AllInterleavings("bankAccount.updateGetAmount")) { while (allInterleavings.hasNext()) { RegularFieldBankAccount bankAccount = new RegularFieldBankAccount(); Thread first = new Thread() { @Override public void run() { bankAccount.update(5); } }; first.start(); int amount = bankAccount.getAmount(); assertThat(amount, anyOf(is(0), is(5))); first.join(); } } } 

As the method getAmount() is either executed before or after the update, the amount can be either 0, the value before the update, or 5, the value after the update.

9. Conclusion

In this article, we described the functionality of the VMLens.

To test a concurrent class, we need to test if the methods of the class are atomic and do not contain data races. We do this by writing a test for each combination of updating and reading methods. In the test, we call the methods in parallel and iterate over all thread interleavings using VMLens.

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.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

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 – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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)