Sub topic 10
Faster warmup with cached method profiles
The earlier chapters moved class loading and linking work out of every run and into a one-time cache build. This chapter covers a second kind of saved work. It is the profiling data the JVM normally collects before it knows which methods deserve optimization. JDK 25 added this as ahead-of-time method profiling (JEP 515), and it builds on the one-step cache creation from the previous chapter.
I assume you can build and use an AOT cache with -XX:AOTCacheOutput and -XX:AOTCache. I also assume you know the tiers of JIT compilation: the interpreter, C1, and C2.
Startup time and warmup time
Startup time is the time until main begins, plus the time to load the classes the application needs. The class-related parts of the AOT cache attack that cost.
Warmup time is the period after startup when the application runs slower than it eventually will. The JVM starts in the interpreter. It counts method invocations and loop iterations, and it records what the code actually does. Only then does it hand hot methods to the JIT compilers.
That recorded behavior is the method profile. It includes:
- which branches are taken often and which are rare,
- which concrete types appear at a virtual call site,
- how often each method is invoked.
The optimizing compiler uses these facts. If a call site has only ever seen one receiver type, the compiler can inline that target and guard it with a cheap type check. If a branch has never been taken, the compiler can leave that path out of the fast code.
Collecting a profile takes time, because the application has to run slowly for a while to generate it. In short-lived processes the application may finish before the JVM has enough information to optimize well.
What the profile cache changes
With JDK 25, the training run records method profiles as well as class data. When you create the cache, those profiles are stored in it. In a production run that uses the cache, the JVM reads the stored profiles. The JIT compilers can then act on information that would otherwise have taken many invocations to collect.
The diagram shows where the saved work sits.
The cache holds data, not machine code. Compiled native code is not in the JDK 25 cache. The JVM still has to run the JIT compilers in every process. The change is that they start with better information and can begin useful work sooner.
| Item | Class cache (JDK 24) | With method profiles (JDK 25) |
|---|---|---|
| Loaded and linked class data | Yes | Yes |
| Heap objects for some JDK classes | Yes | Yes |
| Method execution profiles | No | Yes |
| Compiled native code | No | No |
| Extra command-line flag to use it | None | None |
Enabling it
There is no separate switch. A cache created by a JDK 25 training run contains profiles, and a JDK 25 run that uses the cache reads them. The commands are the ones you already know.
A program that shows warmup
A short example makes the effect visible. The program does the same batch of work five times and prints how long each batch takes. The first batches include warmup. Later batches show steady-state speed.
public class Warm {
static int score(String s) {
return (int) s.chars().filter(Character::isDigit).count();
}
public static void main(String[] args) {
for (int batch = 0; batch < 5; batch++) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 200_000; i++) {
sum += score("item-" + i);
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("batch " + batch + ": " + ms
+ " ms (checksum " + sum + ")");
}
}
}Build the JAR and the cache in one step, as in the previous chapter:
javac Warm.java
jar --create --file warm.jar --main-class Warm Warm.class
# Training run: records classes and method profiles, then writes the cache
java -XX:AOTCacheOutput=warm.aot -cp warm.jar WarmNow compare the two kinds of run. Run each several times, because single timings are noisy.
echo "--- no cache"
java -cp warm.jar Warm
echo "--- with cache"
java -XX:AOTMode=on -XX:AOTCache=warm.aot -cp warm.jar Warm-XX:AOTMode=on makes the JVM fail with an error if it cannot use the cache. Without it, a rejected cache gives you the no-cache timings and you may draw the wrong conclusion.
Expect the first batch with the cache to be shorter than the first batch without it. The later batches should be close to each other, because both runs reach the same optimized code. If the numbers are identical, the gain on this machine is too small to see, or the cache is not being used. Check the second case before anything else.
How to read the results
Measure at two levels, because the cache helps at two levels.
- Whole-process time, from
time java ..., includes class loading savings and warmup savings together. - Per-batch or per-request time, measured inside the program, shows the warmup effect on its own. Class loading savings appear in the first batch too, so the first batch is still not a clean measurement of profiles alone.
To separate the two effects, compare against a JDK 24-style cache or a cache that holds classes only. You can do this by running the same program on JDK 24 and JDK 25. The difference between the JDK 25 improvement and the JDK 24 improvement is roughly the profile contribution, with the caveat that other JDK changes also differ between the two versions.
Also warm up your measurement. The first run after creating a cache may be slower because the operating system has not yet cached the cache file in memory. Discard it, and report the median of several later runs.
CPU counts, not just time
Warmup is partly a CPU cost. The JIT compiler threads compete with the application threads for cores. On a container limited to one or two CPUs, better early profiles can shorten the period when compilation and application work fight over the same core. On a many-core machine the gain in wall-clock time can be smaller, because compilation already happens in parallel. Test with the CPU limit you deploy with.
Designing a training run for profiles
Class loading only needs the training run to touch the classes. Profiles need more. They need the training run to behave like production in the ways the JIT cares about.
- Run the hot paths, many times. A method called once during training has an almost empty profile. Run the request handlers, parsers, or loops enough times that the branch counts and type information are meaningful.
- Use realistic inputs. If production data takes branch A 99% of the time, a training run that always takes branch B teaches the compiler the wrong shape.
- Exercise the types you will see. A call site that sees only
ArrayListin training will be profiled as monomorphic. If production passesLinkedListor an immutable list too, the optimized code will be wrong for those calls. - Keep it deterministic. A training run that finishes by itself, with fixed input, produces a reproducible cache. This also matters for the build pipeline chapter.
- Exit cleanly. The cache is written when the JVM exits normally at the end of the training run. If the process is killed, there may be nothing to write.
A server application needs a driver. A common pattern is a start-up flag or a test harness that sends a few hundred synthetic requests through the real code and then triggers a normal shutdown.
What happens when the profile is wrong
Cached profiles are a starting point, not a promise. The JIT compilers still insert guards, and the JVM still has a mechanism to back out of an optimization whose assumption fails. That mechanism is deoptimization. When production behavior differs from training, the JVM deoptimizes the affected method, returns it to a slower tier, and collects fresh profile data.
The result is a trade-off. A representative training run gives a faster warmup. A misleading one costs some of that gain, because the first compilations of some methods are wasted and must be redone. In general it does not cause incorrect results. Deoptimization exists precisely so that a wrong assumption does not change program behavior.
Interaction with other cache rules
The profile data rides in the same cache file as the class data, so the same validation rules apply. If the JVM rejects the cache because the JDK build, the class path, or a relevant flag differs, you lose class data and profiles together. The checks from the validation chapter still apply, and -XX:AOTMode=on is still the way to turn a silent fallback into an error.
Two practical consequences follow.
- Changing the application JAR invalidates the cache, so regenerate profiles whenever you rebuild. Stale profiles for changed code are not used.
- Changing JIT-related flags, such as limiting compiler tiers, between training and production can change how well the profiles help. Keep the training and production command lines the same except for the cache options.
Limits to keep in mind
- The gain is mainly for short-running and bursty workloads. A service that runs for days spends most of its life in steady state, where cached profiles make no difference.
- The interpreter still runs first. The profiles let the JIT decide sooner, but they do not remove the need to compile.
- Profiles reflect the training workload only. They cannot adapt to a different mix of requests without deoptimization and re-profiling.
- The cache does not store compiled native code in JDK 25, so the JIT work itself still happens in every run.
Exercise
You build a cache with JDK 24 and run the application on JDK 25 with -XX:AOTMode=on -XX:AOTCache=app.aot. Will the run benefit from cached method profiles? Explain why or why not.
Show answer
No. The cache was created by JDK 24, which stores class data only and not method profiles. A cache is also tied to the JVM build that created it, so with -XX:AOTMode=on JDK 25 will most likely reject the file and fail with an error. The fix is to create the cache with the JDK 25 that will run the application, for example with -XX:AOTCacheOutput=app.aot.
Exercise
A web service shows a fast first request after you add the cache, but its second kind of request, handled by code the training run never reached, is still slow for the first several seconds. What is the likely cause, and what change to the training run addresses it?
Show answer
Methods that the training run never executed have no stored profile, so the JVM profiles them from scratch in the production run as before. Extend the training run to send realistic requests of every important kind, enough times that branch and type information is meaningful, then rebuild the cache.
Exercise
Why does the chapter recommend measuring per-batch time inside the program as well as using time java ...?
Show answer
time measures the whole process, which mixes class loading savings with warmup savings and includes JVM startup and shutdown. Per-batch timing inside the program shows how fast the work itself runs during warmup, so you can see whether the early batches get faster with the cache.