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

Micrometer Gauges are a convenient way to expose the state of in-memory objects as application metrics. However, when they aren’t configured correctly, they may produce unexpected results, such as returning NaN instead of the actual value. This affects how a metric appears in Prometheus or any other metrics backend.

In this tutorial, we’ll reproduce a common scenario where a gauge reports NaN due to garbage collection. Then, we’ll discuss the underlying cause and fix the issue by maintaining strong references to the monitored object.

2. Reproducing the NaN Issue

Let’s suppose we want to monitor the state of a Java object and expose it via the Spring Boot Actuator.

Firstly, let’s add the spring-boot-starter-actuator dependency to the project, which brings in the Micrometer dependency, too:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Now, we can inject MeterRegistry in the service class and use it to register a Gauge that observes an object. For example, we can create and register the Gauge when the Spring application is fully initialized by listening for the ApplicationReadyEvent:

@Service
class FooService {

    private final MeterRegistry registry;

    // constructor

    @EventListener(ApplicationReadyEvent.class)
    public void setupGauges() {
        setupWeakReferenceGauge();
    }

    private void setupWeakReferenceGauge() {
        Foo foo = new Foo(10);

        Gauge.builder("foo.weak", foo, Foo::value)
          .description("Foo value - weak reference (will show NaN after GC)")
          .register(registry);
    }
  
    record Foo(int value) {
    }

}

If we verify the foo.weak meter now, we could expect to see a value of ten. However, if we start the application locally and perform a GET request to /actuator/metrics/foo.weak, we may immediately or eventually see a value of NaN:

{
    "name": "foo.weak",
    "description": "Foo value - weak reference (will show NaN after GC)",
    "measurements": [
       {
          "statistic": "VALUE",
          "value": "NaN"
      }
    ],
    "availableTags": []
}

Thus, we get data from the gauge that isn’t useful.

3. Understanding the Root Cause

To understand why the Gauge returns NaN, we need to look at two things:

  • how Java garbage collection works with different reference types
  • how Micrometer implements gauges

In Java, we can reference an object in different ways. A strong reference is the normal type of reference and prevents the object from being garbage collected as long as it exists. Conversely, weak references don’t prevent garbage collection. When the JVM needs memory, it’s free to reclaim objects that are only weakly reachable.

Micrometer’s Gauge has a design that aims to avoid memory leaks. Therefore, it doesn’t keep a strong reference to the monitored object by default. Instead, Gauge stores a weak reference and calls the provided value function when the metric is scraped.

In the example above, the Foo instance is created inside the setupWeakReferenceGauge method and isn’t stored anywhere else. Once that method finishes, there are no strong references to the object. This means the Foo instance becomes eligible for garbage collection almost immediately. When the garbage collector removes the object, the weak reference held by the gauge is cleared. Later, when the actuator endpoint tries to read the metric value, Micrometer can no longer access the object, so it reports the value as NaN.

4. Using Strong References

To prevent the gauge from returning NaN, we need to make sure that the monitored object isn’t garbage collected. The simplest way to do this is to keep a strong reference to it.

For instance, we could store Foo as a field in the service class. On the other hand, we can keep the code as it is and simply leverage .strongReference(true) from Gauge.Builder API:

private void setupStrongReferenceGauge() {
    Foo foo = new Foo(10);

    Gauge.builder("foo.strong", foo, Foo::value)
      .description("Foo value - strong reference (will persist)")
      .strongReference(true)
      .register(registry);
}

That’s it! Let’s verify the value of the new meter using the path /actuator/metrics/foo.strong:

{
    "name": "foo.strong",
    "description": "Foo value - strong reference (will persist)",
    "measurements": [
       {
          "statistic": "VALUE",
          "value": 10
      }
    ],
    "availableTags": []
}

Now, we again see a useful value.

5. Conclusion

In this article, we explored why Micrometer gauges may return NaN values when monitoring in-memory objects and how this behavior is related to the Java garbage collection and Micrometer’s use of weak references.

We reproduced the issue using Spring Boot Actuator, analyzed the root cause, and demonstrated how to fix it by keeping a strong reference to the monitored object or explicitly enabling strong references in the Gauge builder. With these approaches, we can ensure that metrics remain accurate and reliable when exposed to Prometheus or any other monitoring system.

As always, the code presented in this article is available over on GitHub.

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=Java)
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)