archive2024

Java startup time: CDS, Spring AOT and GraalVM native image

When Java startup time matters and when it does not, how to measure it honestly, and what CDS, Spring Boot 3.3 CDS support, Spring AOT, GraalVM native image and CRaC each give you.

I had to decide whether a small Spring Boot service should run as a scale-to-zero container. The first question was how long the first request waits after a cold start. I looked at the options available today (Java 21, Spring Boot 3.3) and wrote down what each one does and costs.

I give no timings here. The gain depends on the app, the number of classes, the container CPU limit and the disk. Measure your own app with the method below.

When startup matters

Startup time matters when the JVM starts often and somebody waits for it:

  • Scale-to-zero platforms and serverless functions. The first request after idle pays the whole startup.
  • Autoscaling under load. New instances should take traffic quickly, not after the spike is over.
  • CLI tools. A command that takes a second before it prints anything feels broken.
  • Tests. Integration tests that start a Spring context many times, and CI jobs that run them on every push.

It matters much less for a long-running service that starts once a week behind a load balancer with rolling deploys. There, startup is a few seconds out of days, and peak throughput, memory and simple operations matter more. If this is your case, you can probably stop reading and leave the defaults alone.

Measure time to first request

Spring Boot prints a line like Started DemoApplication in N seconds (process running for M). This number is useful, but it is not what the user sees. It does not include all of JVM startup, and it is printed before the first request runs. The first request is often slow too: lazy beans, the first database connection, the first JIT compilation of the request path.

I measure from process start to the first successful HTTP response. On Linux:

#!/usr/bin/env bash
# time-to-first-request.sh  (Linux: date +%s%N gives nanoseconds)
start=$(date +%s%N)
java "$@" > app.log 2>&1 &
pid=$!
until curl -fs http://localhost:8080/actuator/health > /dev/null; do
  sleep 0.02
done
end=$(date +%s%N)
echo "first response after $(( (end - start) / 1000000 )) ms"
echo "RSS: $(ps -o rss= -p $pid) KB"
kill $pid

Run it like ./time-to-first-request.sh -jar target/app.jar. If you do not have Actuator, use any cheap endpoint. Better: use a real endpoint that touches the database, because that is what the first user calls.

Some rules I follow:

  • Run it several times and look at the spread. The first run after a build is slower because files are not in the page cache.
  • Run it with the same CPU and memory limits as production, for example inside the container with --cpus. Startup on a 1 CPU container is very different from a laptop with many cores.
  • Also record memory (RSS). Some options trade memory for speed, or the other way.

Class Data Sharing (CDS)

When the JVM starts, it reads class files, parses and verifies them, and builds internal structures. CDS saves those structures in an archive file and maps the file into memory at the next start. It is a normal HotSpot feature, so you keep the normal JIT and GC.

There are a few levels:

  • The JDK ships a default CDS archive for its own classes (since JDK 12). You already use it.
  • AppCDS adds your application and library classes (open in OpenJDK since JDK 10).
  • A dynamic archive can be written at the end of a training run with -XX:ArchiveClassesAtExit (since JDK 13). This is the easiest way.

The basic flow:

# 1. training run: start the app, exercise it, stop it; the archive is written at exit
java -XX:ArchiveClassesAtExit=app.jsa -jar app.jar

# 2. normal runs use the archive
java -XX:SharedArchiveFile=app.jsa -jar app.jar

Since JDK 19 there is also -XX:+AutoCreateSharedArchive -XX:SharedArchiveFile=app.jsa, which creates or refreshes the archive by itself when it is missing or stale.

The archive is strict. It must be used with the same JVM build, and the classpath must match the one from the training run. If it does not match, the JVM silently ignores the archive by default. To check that classes really come from the archive:

java -XX:SharedArchiveFile=app.jsa -Xlog:class+load:file=classload.txt -jar app.jar
grep -c "shared objects file" classload.txt

If almost nothing comes from the shared file, something does not match. -Xshare:on makes the JVM fail instead of ignoring the archive, which is useful while you set it up.

There is one more problem with Spring Boot. CDS does not work well with classes inside nested jars of a fat jar. You need a plain classpath of normal jar files.

Spring Boot 3.3 CDS support

Spring Boot 3.3 (May 2024) added two things that make CDS practical. The Spring team describes them in this blog post and in the CDS how-to.

First, the executable jar can extract itself into a CDS-friendly layout with the tools jar mode:

java -Djarmode=tools -jar target/app.jar extract --destination application

This writes application/app.jar plus a lib/ folder, with a manifest classpath that points to the libraries.

Second, Spring Framework 6.1 has a property that stops the app right after the context refresh. That is a good point to end a training run, because most classes are loaded, but no traffic is needed:

cd application
java -XX:ArchiveClassesAtExit=app.jsa -Dspring.context.exit=onRefresh -jar app.jar
java -XX:SharedArchiveFile=app.jsa -jar app.jar

Be careful with the training run. Beans are created, so anything that runs at bean creation also runs here. If a bean connects to a database at startup, the training run needs that database or the bean must handle it. Run the training step in your Dockerfile with the same base image and the same paths as the final container, otherwise the archive will not match.

If you build images with buildpacks, setting BP_JVM_CDS_ENABLED=true in the image build makes the buildpack do the training run and use the archive for you.

Note that the tools jar mode does not work with a “fully executable” jar that has a launch script in front of it. Turn that option off if you use it.

Spring AOT on the JVM

Spring AOT processing runs at build time. It evaluates the configuration, decides which beans exist, and generates Java code that registers them directly. At runtime Spring skips much of the reflection and condition checking.

AOT is required for native image, but you can also use it on a normal JVM. With Maven and the Spring Boot parent, the native profile runs the process-aot goal; then start the jar with:

./mvnw -Pnative package
java -Dspring.aot.enabled=true -jar target/app.jar

The cost: the bean graph is fixed at build time. @Profile and @ConditionalOnProperty decisions are made during the build, so you cannot switch profiles at runtime the way you used to. Some libraries that do clever things with reflection or bean definitions may not work. AOT and CDS can be used together: add -Dspring.aot.enabled=true to both the training run and the normal runs.

GraalVM native image

Native image compiles the app ahead of time into a single executable. At runtime there is no class loading from jars and no JIT warm-up. Startup is much faster and memory use is usually lower. Spring Boot 3 supports it officially.

# Maven, with GraalVM native-image on the PATH
./mvnw -Pnative native:compile
./target/app

# or build a container image with buildpacks (no local GraalVM needed)
./mvnw -Pnative spring-boot:build-image

# Gradle
./gradlew nativeCompile

What it costs:

  • Build time and build memory. The build analyses the whole program. It takes minutes, not seconds, and needs several GB of RAM. Small CI runners may fail with out-of-memory. Keep the normal JVM build for the inner development loop.
  • Closed world. Everything reachable must be known at build time. Reflection, dynamic proxies, resources and serialization need metadata. Spring AOT generates most of it. For your own code, use RuntimeHints or @RegisterReflectionForBinding. For libraries, the GraalVM reachability metadata repository covers many popular ones.
  • Things that break. Libraries that generate bytecode at runtime, Java agents, some logging setups, code that reads classes by name from config. Profiles and conditions are fixed at build time, like with AOT on the JVM. Errors often show up only at runtime as a missing class or method, so run the tests as native too (./mvnw -PnativeTest test, or ./gradlew nativeTest).
  • Peak throughput. There is no JIT. The code is compiled once, without runtime profiles. For a long-running service under steady load, a warmed-up HotSpot JVM can be faster. Oracle GraalVM has profile-guided optimisation to close part of the gap, but that adds another build step.
  • Tooling. Heap dumps, JFR and debuggers work differently or with limits. Check what your monitoring needs before you commit.

CRaC

CRaC (Coordinated Restore at Checkpoint) takes another way. You start the app on a normal JVM, warm it up, take a checkpoint of the whole process, and later restore from that snapshot. You keep the JIT, and the restored process is already warm.

As of now it is an OpenJDK project, not part of the mainline JDK. You need a JDK build with CRaC, for example from Azul, and it works on Linux only. Spring Boot 3.2 added support: -Dspring.context.checkpoint=onRefresh takes a checkpoint after the context starts, and Spring handles closing and reopening resources like connection pools. The checkpoint image contains the process memory, so treat it as a secret if your app holds credentials. Restore needs the same CPU architecture and environment as the checkpoint. I have not tried it beyond a demo app, so I would not use it in production yet.

Which one to use

Situation My choice
Long-running service, rolling deploys Nothing special. Maybe CDS because it is cheap.
Container that scales often, normal Spring app CDS with Spring Boot 3.3 extraction. Add AOT on the JVM if you do not need runtime profiles.
Scale to zero, cold start must be very short Native image, if your libraries support it and you test the native build in CI
CLI tool written in Java Native image
Slow integration tests Fix the test setup first (context caching, fewer different contexts). CDS on the test JVM can help a bit.
Need warm JIT immediately after start, Linux only CRaC, if you accept a non-mainline JDK

I started with CDS for my service. It needs no code change, it keeps the normal JVM, and the work is a few lines in the Dockerfile. If the time to first request is still too long under the real container limits, native image is the next step, and I will measure again before I pay its build cost.

For the image side of this, the layered jar setup from an older post still applies, and the container memory settings matter as much as startup when containers are small.