Sub topic 5
Choosing a representative training run
Prerequisites
This chapter assumes you can compile a class and package it into a JAR. It also assumes you know the classpath, and you have seen the three-step record, create and run workflow from the previous chapter. You should know that the JVM loads classes lazily, the first time code needs them.
What the training run decides
The AOT cache is built from evidence. During the record step, the JVM runs your application once and notes every class it loads and links. The create step turns that list into a cache file. At run time, the JVM can take those classes from the cache instead of reading, parsing and verifying them again.
So the training run defines the cache. A class the training run never touched is not in the cache. The JVM still loads it at run time from the JAR or the JDK in the normal way, and your program stays correct. It just doesn't get faster.
That makes the training run a design decision with two goals:
- Reach the classes your application needs on a typical start.
- Finish quickly, repeatably and without harmful side effects, because you will run it in every build.
A good training run is not a load test. You want the classes used while starting up and handling the first typical requests or tasks. You don't want to run for an hour.
What counts as representative
Ask what your application does between java and "ready to do useful work". For most programs that includes the following.
- Framework bootstrap. Dependency injection containers, configuration binding, logging setup and web server startup load thousands of classes. This is usually where the largest saving sits.
- First-use library paths. The first call to a JSON mapper, an HTTP client, a regular expression,
String.formatorjava.timeformatting pulls in many classes. Each of these paths loads classes only when it first runs. - Lambdas and streams. The first lambda or method reference in a JVM triggers generation of supporting classes. Streams add a large set of pipeline classes. The AOT cache can store these, but only if the training run executes the code that creates them.
- Typical request or task handlers. If the first real request takes 300 ms because of class loading, the training run should send that kind of request.
Rarely used code is the other side of the trade. An admin report that runs once a month does not need to be in the cache. Including it costs build time and some cache size. Leaving it out costs nothing at startup, because that path would load normally anyway.
A training-friendly program
The simplest way to get a deterministic run is to build it into the application. The program below reads a mode argument. With --train, it runs a representative workload on built-in sample data and exits. Without it, it runs normally.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Report {
private static final Pattern LINE = Pattern.compile("(\\w+),(\\d{4}-\\d{2}-\\d{2}),(\\d+)");
record Sale(String item, LocalDate date, int units) {}
static List<Sale> parse(List<String> lines) {
return lines.stream()
.map(LINE::matcher)
.filter(Matcher::matches)
.map(m -> new Sale(m.group(1), LocalDate.parse(m.group(2)), Integer.parseInt(m.group(3))))
.toList();
}
static String summarize(List<Sale> sales) {
Map<String, Integer> totals = sales.stream()
.collect(Collectors.groupingBy(Sale::item, Collectors.summingInt(Sale::units)));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("d MMM yyyy");
return totals.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> String.format("%-8s %5d (as of %s)", e.getKey(), e.getValue(),
sales.get(0).date().format(fmt)))
.collect(Collectors.joining("\n"));
}
public static void main(String[] args) {
boolean train = args.length > 0 && args[0].equals("--train");
List<String> input = List.of(
"apple,2026-11-01,10",
"pear,2026-11-02,4",
"apple,2026-11-03,7",
"bad line");
// In a real application, normal mode would read a file or a socket.
// Training mode uses fixed data so it needs no external resources.
System.out.println(summarize(parse(input)));
if (train) {
System.out.println("training run complete");
}
}
}This workload touches regular expressions, records, streams, collectors, java.time parsing and formatting, and String.format. All of these are classic sources of startup class loading.
Build and train it:
javac Report.java
jar --create --file report.jar --main-class Report Report.class 'Report$Sale.class'
java -XX:AOTMode=record -XX:AOTConfiguration=report.aotconf -cp report.jar Report --train
java -XX:AOTMode=create -XX:AOTConfiguration=report.aotconf -XX:AOTCache=report.aot -cp report.jar
java -XX:AOTCache=report.aot -cp report.jar ReportThe arguments after the main class (--train) only steer your program. The cache does not record them, so the production run can omit them.
Checking what the training run covered
Do not assume the training run was good. Check it. Compare where classes load from in a cached run:
java -XX:AOTCache=report.aot -Xlog:class+load -cp report.jar Report > load.log
grep -c "shared objects file" load.log
grep -v "shared objects file" load.log | grep "source:"The first command counts classes served from the cache. The second lists classes that came from somewhere else, typically jrt:/ for the JDK image or file: for your JAR. Each line in that list is a class the cache missed. Read the names. If you see framework classes you expected to be cached, the training run never reached the code that uses them. If you see only a few odd classes, the run is good enough.
If the list contains classes from your own code paths, extend the training workload to call them, then record again. Repeat until the remaining misses are things you accept, such as rarely used features.
Some classes legitimately remain outside the cache. Classes defined at run time by custom class loaders or by bytecode generators are not covered by the basic cache. Chapter 12 covers this under limitations.
Rules the training run must follow
The cache is only usable if the production run matches the conditions of the training run. These matter when you design the training step.
- Same JDK build. Train and run with the same JDK version and vendor build. A cache from a different JDK is rejected.
- Compatible classpath. The production classpath must match the training classpath, or extend it with extra entries at the end. If the JVM sees different entries, or JAR files that changed since training, it rejects the cache. Train with the exact JAR you will ship, not with a
target/classesdirectory. - Same relevant JVM options. Options that change how classes are laid out or loaded can invalidate the cache. Use the production flags during training, except for the AOT flags themselves.
- Normal exit. The configuration file is written when the JVM exits. A training run killed with
SIGKILLor one that hangs produces no usable record. A call toSystem.exitis fine.
Chapter 8 explains the validation in more detail. For now, treat "train with the artifact and flags you ship" as the rule.
Making training deterministic
Training runs happen in CI, so they must be repeatable and bounded. A few practices help.
- Use fixed inputs. Bundle sample data in the JAR or generate it in code. Random data or the current date can change the paths taken, so different builds produce different caches.
- Bound the run. Add a limit on the number of requests, or an explicit shutdown after the workload. A server that waits forever for input never produces a record. For a web service, start it, send a small set of requests from a script, then stop it with a normal shutdown signal such as
SIGTERM. - Fail the build on a bad run. If the training process exits with an error, stop. A cache built from a crashed run covers only the code that ran before the crash.
- Keep it fast. Ten to thirty seconds is typical. A longer run adds little, because class loading is front-loaded and later requests mostly reuse classes already loaded.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Training only `--help` or a trivial path | Cache holds only a few classes, small gain | Run a real workload on sample data |
| Training with a different JAR or classpath order | JVM rejects the cache at run time | Train with the shipped artifact |
| Running the server and forgetting to stop it | No configuration file is written | Bound the run, stop it with a normal shutdown |
| Exercising every feature, including admin tools | Larger cache, longer build, little startup gain | Cover startup and typical use only |
| Training against production services | Unwanted side effects | Add a training mode with test resources |
| Never checking the class+load log | A poor cache goes unnoticed | List classes not loaded from the cache |
Over-training versus under-training
Under-training is the common failure, and the log check above finds it. Over-training is milder. Extra classes make the cache file larger and the create step slower. The JVM maps the file into memory, so classes that are never used cost address space and a little disk, but not class loading time.
A reasonable rule: include every code path that runs in the first few seconds of a normal production life. Add paths for features that most users hit early. Leave out everything else, and use the log check to decide whether a missing class justifies a longer run.
Exercise
Your service's training run starts the HTTP server and then exits when a script sends SIGTERM. The cached run is only slightly faster than the uncached one. The log shows that the JSON mapper classes and your request handler classes load from the JAR, not the cache. What is the most likely cause, and what do you change?
Show answer
The training run started the server but sent no requests, so the request handling code (the handler and the JSON mapper, which load lazily on first use) never ran and was not recorded. Extend the training script to send a few representative requests, such as one for each common endpoint with sample payloads, before sending SIGTERM. Record and create the cache again, then recheck the class+load log to confirm those classes now load from the shared objects file.
Exercise
A teammate trains the cache with java -XX:AOTMode=record ... -cp target/classes Report --train but ships report.jar and runs with -cp report.jar. Why is this risky, and what should change?
Show answer
The production classpath differs from the training classpath, so the JVM may reject the cache and run without it. Training must use the same artifact and classpath that will be deployed. Build report.jar first, then record, create and run with -cp report.jar.