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 – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
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

1. Introduction

Every time we start a Java app, the JVM rebuilds the same classes from scratch, which shows up in the startup time. The Ahead-of-Time (AOT) cache lets us use caching to reuse the build’s output, so later runs start faster. In this tutorial, we’ll use the AOT cache on a sample app. We’ll build a cache for the app, confirm that the JVM really uses the AOT cache, and then train the cache. We’ll use JDK 26 for this tutorial.

2. What Is the Ahead-of-Time Cache in Java

The feature first arrived in JDK 24 through JEP 483, as the first piece of Project Leyden. JDK 25 added method profiles so the JIT can warm up sooner, and JDK 26 lifted the old garbage-collector limit through JEP 516. In the following sections we look at how the cache achieves what it claims. Let’s consider a small catalog service that we already have on hand: its code lives in one app.jar, packaged next to the handful of library JARs it depends on, and it boots through a com.example.App main class. We’ll build a cache for the app, confirm the JVM uses the cache, and then train well enough to see speed gains in its loading time.

2.1. How the Cache Speeds Up Startup

Normally the JVM reads, loads, and links each class as the app boots, and it repeats that work on every run. The cache changes this by saving those classes once, so that on the next run they come straight from disk instead of being rebuilt. Because our cache captures the work of one specific app, we reuse it whenever we run that same app. The speedup comes from moving the heavy lifting earlier, which leaves the classes ready the moment the program starts.

2.2. Training and Production Runs

Before we discuss the caching workflow, it helps to discuss two words we’ll lean on throughout: training and production. A training run is one we carry out deliberately, ahead of time, to watch the app and build the cache from what we observe, so it never serves real users. A production run, by contrast, is the real deployment that serves traffic, and it loads the finished cache to start faster.

2.2. The Three-Phase Workflow

The original workflow of the caching process runs in three phases, namely record, create, and run. Each step feeds the next. We start with the record phase. Here the JVM watches the app and writes what it sees to a configuration file. We switch it on with a flag and name the file through a configuration:

java -XX:AOTMode=record -XX:AOTConfiguration=app.aotconf \
  -cp app.jar com.example.App ...

As it runs, this phase notes which classes load and which methods turn hot, then stores those findings in app.aotconf. Once the file is created, the next step comes to effect. We feed the file into the create phase, which turns the recorded data into a real cache:

java -XX:AOTMode=create -XX:AOTConfiguration=app.aotconf \
  -XX:AOTCache=app.aot -cp app.jar

Once the cache exists, the run phase simply points at it and benefits from the faster start:

java -XX:AOTCache=app.aot -cp app.jar com.example.App ...

We observe here that since the classes are already prepared, this final run skips the work the first two phases did. In the three phases discussed above, the record and create steps make up the training side, while the run phase stands in for production.

3. How to Build the Cache

We should now focus on building the cache. Running the three phase workflow everytime is not very developer friendly. Also, it’s more than most apps need. In the following sections, we discuss how JDK 25 folded and converged the cache building steps.

3.1. Making the Cache in One Step

We hand a destination to -XX:AOTCacheOutput, and the JVM builds the cache for us. It shuts down and outputs it in the mentioned destination:

java -XX:AOTCacheOutput=app.aot \
  -cp app.jar com.example.App ...

If we’d rather keep the training command separate from deployment, JEP 514 offers a two-step variant that records once and then reuses the cache:

java -XX:AOTCacheOutput=app.aot \
  -cp app.jar com.example.App ...

java -XX:AOTCache=app.aot -cp app.jar com.example.App ...

For the majority of apps, this shorter path is what is used.

3.2. Splitting the Work for Small Machines

Convenient as the one-step path is, it comes with a memory bill. While it assembles the cache, the JVM spins up a second heap the same size as the training heap, so the peak demand climbs to roughly twice the size we set. With -Xms2g -Xmx2g, for instance, the machine needs about 4 GB before it finishes. That overhead is why the three-phase split still earns its place on small cloud servers. We can record on a modest instance that mirrors production, and then assemble the cache on a larger one where there’s room to spare. The recording stays faithful to the real environment, while the heavy assembly runs where memory is plentiful.

4. How to Shape the Cache Our App Needs

A cache only pays off when the training run and the production are in line. And this require a handful of conditions to be satisfied.

4.1. Keeping Training and Production aligned

Let’s see a few rules which ensure the training and production runs align:

  • the JAR timestamps stay the same across training runs
  • both runs use the same JDK, hardware, and OS
  • the training run acts like the real one, so the busy paths match
  • the classpath is a list of plain JARs, with no folders, wildcards, or nested JARs
  • the production classpath holds at least what the training one holds
  • no JVMTI agent adds to the boot or system class search at run time

Following the above, we should ideally see the deployment run produce the same result as training, and perhaps faster.

4.2. Checking That the Cache Is Valid

Rather than trusting the cache blindly, we can ask the JVM to treat a broken setup as a hard failure. Adding -XX:AOTMode=on does exactly that, turning a silent fallback into a clear error:

java -XX:AOTCache=app.aot -XX:AOTMode=on \
  -cp app.jar com.example.App ...

So if the cache goes missing, or one of the conditions above slips, the run stops instead of quietly dropping the speedup. It’s worth remembering, though, that the cache is valid for a single build only. A code change, a new or updated library, or a JDK upgrade each invalidate it. This means we regenerate the cache alongside every build. And when the expected gain fails to appear, we can trace what the cache loads by adding -Xlog:aot,class+path=info.

5. Tips for Good Training Runs

Of the three phases we’ve covered, the training run is the one that carries the real weight. The create and run phases are mostly mechanical: they package whatever the training run observed and replay it on startup, without judging whether that was the right thing to capture. So the cache is only ever as good as the run that built it. Let’s discuss a few tips for architecting a good training run.

5.1. Matching What Production Loads

There’s a natural trade-off between how realistic a training run is and how easy it is to stage. A true production run opens connections, queries the database, and writes logs, all of which are difficult to reproduce. Therefore a synthetic run that follows the same paths usually strikes the better balance. What matters most is overlap. The closer the training run loads the same classes as production, the better the startup we get. To see that overlap, we can list everything a run loads by adding -verbose:class when we launch it. A light smoke test gives us a tidy way to drive those results. It exercises a normal startup without pulling in heavy suites, which keeps the cache lean. We named it in BDD style while keeping the framework minimal:

class StartupSmokeTest {

    @Test
    void givenFreshApplication_whenMainPathRuns_thenCoreServicesInitialize() {
        App app = App.bootstrap();

        assertTrue(app.isReady());
        assertNotNull(app.catalogService());
    }
}

We rely on tests like this for the common startup paths. Also, we are deliberately leaving the stress and regression suites out of the training run.

5.2. Finding Hot Methods With JFR

Now and then a method matters at run time yet never surfaces during a shallow training run. The JDK Flight Recorder is how we catch those cases. We begin by enabling the class-load event, then record the app from the moment it starts. Let’s start by first enabling the event: jfr configure jdk.ClassLoad#enabled=true Now, let’s start the recording: java -XX:StartFlightRecording:settings=custom.jfc,duration=60s,filename=/tmp/AOT.jfr With a recording in hand, we can check the loaded classes and the hottest methods:

jfr print --events "jdk.ClassLoad" /tmp/AOT.jfr
jfr view hot-methods /tmp/AOT.jfr

If a hot method turns out to be missing, we extend the smoke test to walk through it. We start by leaning on a temporary folder, then a local network, or a mocked database wherever the path demands one.

6. Best Practices

A healthy cache really comes down to a few recurring habits and practices:

  • Validity, since every rebuild or JDK upgrade calls for a fresh cache
  • Portability, since the cache is bound to one JVM and platform
  • Coverage, since the training run has to walk the normal startup paths
  • Setup, since both the JAR and the cache should run with least privilege

7. Conclusion

In this tutorial, we followed the whole AOT cache promise. We built a cache both in a single step and across three phases. Additionally, we confirmed that the JVM was really using it, and then trained it with a light smoke test so it covered the paths that count. Taken together, these steps make the cache easy to add and just as easy to keep current.

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

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 Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments