Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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 – 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 – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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 – Reactive – NPI(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

1. Overview

Optimizing code for performance is a key part of programming, especially when dealing with expensive operations or data retrieval processes.  One effective way of improving performance is caching.

The Project Reactor library provides a cache() method to cache expensive operations or data that hardly changes to avoid repeat operations and improve performance.

In this tutorial, we’ll explore memoization, a form of caching, and demonstrate how to use Mono.cache() from the Project Reactor library to cache the results of the HTTP GET request to JSONPlaceholder API. Also, we’ll understand the internals of Mono.cache() method through a marble diagram.

2. Understanding Memoization

Memoization is a form of cache that stores the output of expensive function calls. Then, it returns the cached result when the same function call occurs again.

It’s useful in a case involving recursive functions or computations that always produce the same output for a given input.

Let’s see an example that demonstrates memoization in Java using the Fibonacci sequence. First, let’s create a Map object to store the cache the result:

private static final Map<Integer, Long> cache = new HashMap<>();

Next, let’s define a method to compute the Fibonacci sequence:

long fibonacci(int n) {
    if (n <= 1) {
        return n;
    }

    if (cache.containsKey(n)) {
        return cache.get(n);
    }

    long result = fibonacci(n - 1) + fibonacci(n - 2);
    logger.info("First occurrence of " + n);
    cache.put(n, result);

    return result;
}

In the code above, we check if the integer n is already stored in the Map object before further computation. If it’s already stored in the Map object, we return the cached value. Otherwise, we compute the result recursively and store it in the Map object for future use.

This method significantly improves the performance of the Fibonacci calculation by avoiding redundant computations.

Let’s write a unit test for the method:

@Test
void givenFibonacciNumber_whenFirstOccurenceIsCache_thenReturnCacheResultOnSecondCall() {
    assertEquals(5, FibonacciMemoization.fibonacci(5));
    assertEquals(2, FibonacciMemoization.fibonacci(3));
    assertEquals(55, FibonacciMemoization.fibonacci(10));
    assertEquals(21, FibonacciMemoization.fibonacci(8));
}

In the test above, we invoke the fibonacci() to compute sequences.

3. Describing Mono.cache() with Marble Diagram

The Mono.cache() operator helps cache the result of a Mono publisher and return the cached value for subsequent subscriptions.

The marble diagram helps to understand the internal details of reactive classes and how they work. Here’s a marble diagram that illustrates the behavior of the cache() operator:

marble diagram for mono cache

In the image above, the first subscription to the Mono publisher emits data and caches it. Subsequent subscriptions retrieve the cached data without triggering a new computation or data fetch.

4. Example Setup

To demonstrate the usage of Mono.cache(), let’s add reactor-core to the pom.xml:

<dependency>
    <groupId>io.projectreactor</groupId>
    <artifactId>reactor-core</artifactId>
    <version>3.6.5</version>
</dependency>

The library provides operators, Mono, Flux, etc., to implement reactive programming in Java.

Also, let’s add spring-boot-starter-webflux to the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>3.2.5</version>
</dependency>

The above dependency provides the WebClient class to consume an API.

Also, let’s see a sample response when we get a GET request to https://jsonplaceholder.typicode.com/users/2:

{
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette"
    // ...
}

Next, let’s create a POJO class named User to deserialize the JSON response from the GET request:

public class User {
    private int id;
    private String name;

    // standard constructor, getter and setter
}

Furthermore, let’s create a WebClient object and set the base URL for the API:

WebClient client = WebClient.create("https://jsonplaceholder.typicode.com/users");

This serves as the base URL for the HTTP response that will be cached using the cache() method.

Finally, let’s create an AtomicInteger object:

AtomicInteger counter = new AtomicInteger(0);

The object above helps to keep track of the number of times we make a GET request to the API.

5. Fetching Data Without Memoization

Let’s start by defining a method that fetches a user from the WebClient object:

Mono<User> retrieveOneUser(int id) {
    return client.get()
      .uri("/{id}", id)
      .retrieve()
      .bodyToMono(User.class)
      .doOnSubscribe(i -> counter.incrementAndGet())
      .onErrorResume(Mono::error);
}

In the code above, we retrieve a user with a specific ID and map the response body to a User object. Also, we increment the counter on every subscription.

Here’s a test case that demonstrates fetching a user without caching:

@Test
void givenRetrievedUser_whenTheCallToRemoteIsNotCache_thenReturnInvocationCountAndCompareResult() {
    MemoizationWithMonoCache memoizationWithMonoCache = new MemoizationWithMonoCache();

    Mono<User> retrieveOneUser = MemoizationWithMonoCache.retrieveOneUser(1);
    AtomicReference<User> firstUser = new AtomicReference<>();
    AtomicReference<User> secondUser = new AtomicReference<>();

    Disposable firstUserCall = retrieveOneUser.map(user -> { 
          firstUser.set(user);
          return user.getName();
      })
      .subscribe();

    Disposable secondUserCall = retrieveOneUser.map(user -> { 
          secondUser.set(user);
          return user.getName();
      })
      .subscribe();

    assertEquals(2, memoizationWithMonoCache.getCounter());
    assertEquals(firstUser.get(), secondUser.get());
}

Here, we subscribe to the retrieveOneUser Mono twice, and each subscription triggers a separate GET request to the WebClient object. We assert that the counter increments twice.

6. Fetching Data With Memoization

Now, let’s modify the previous example to leverage Mono.cache() and cache the result of the first GET request:

@Test
void givenRetrievedUser_whenTheCallToRemoteIsCache_thenReturnInvocationCountAndCompareResult() {
    MemoizationWithMonoCache memoizationWithMonoCache = new MemoizationWithMonoCache();

    Mono<User> retrieveOneUser = MemoizationWithMonoCache.retrieveOneUser(1).cache();
    AtomicReference<User> firstUser = new AtomicReference<>();
    AtomicReference<User> secondUser = new AtomicReference<>();

    Disposable firstUserCall = retrieveOneUser.map(user -> {
          firstUser.set(user);
          return user.getName();
      })
      .subscribe();

    Disposable secondUserCall = retrieveOneUser.map(user -> {
          secondUser.set(user);
          return user.getName();
      })
      .subscribe();

    assertEquals(1, memoizationWithMonoCache.getCounter());
    assertEquals(firstUser.get(), secondUser.get());
}

The major difference from the previous example is that we invoke the cache() operator on the retrieveOneUser object before subscribing to it. This caches the result of the first GET request, and subsequent subscriptions receive the cached result instead of triggering a new request.

In the test case, we assert that the counter increment once since the second subscription uses the cached value.

7. Setting a Cache Duration

By default, Mono.Cache() caches the result indefinitely. However, in a scenario where the data could become stale over time, it’s essential to set a cache duration:

// ... 
Mono<User> retrieveOneUser = memoizationWithMonoCache.retrieveOneUser(1)
  .cache(Duration.ofMinutes(5));
// ...

In the code above, the cache() method accepts an instance of Duration as a parameter. The cached value will expire after 5 minutes, any subsequent subscriptions after will trigger a new GET request.

8. Conclusion

In this article, we learned the key concept of memorization and its implementation in Java using the Fibonacci sequence example. Then, we deep dive into the usage of Mono.cache() from the Project Reactor library and demonstrate how to cache the results of HTTP GET requests.

Caching is a powerful technique for improving performance. However, it’s essential to consider cache invalidation strategies to ensure that stale data is not served indefinitely.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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 Jackson – NPI EA – 3 (cat = Jackson)