Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 119 ยท Architecture and Deployment

Native Images with GraalVM

Compile Java to a native executable with GraalVM Native Image - how ahead-of-time compilation works, why reflection needs metadata, Spring AOT, build commands and trade-offs.

A normal Java service pays a "warm-up tax" every time it starts. The JVM boots, loads thousands of classes, verifies their bytecode, interprets methods slowly at first, and only later compiles the hot ones into fast machine code. For a service that runs for weeks this tax is irrelevant. For a function that must answer a request after being scaled up from zero, a command-line tool, or a fleet of tiny containers where every megabyte costs money, it is painful.

GraalVM Native Image removes the tax by doing the work earlier. It analyzes your application at build time and compiles it ahead of time (AOT) into one standalone executable that contains your code, the parts of the JDK you use, and a small runtime. There is no JVM to start, no class loading and no JIT warm-up: a Spring Boot service that needs several seconds on the JVM can be ready in well under a second. The price is a slower build, a stricter programming model, and a different set of tuning knobs. This lesson explains the model, the reflection problem that surprises everybody, how Spring Boot helps, and when native images are worth it.

GraalVM itself is not installed in this course's code runner, so commands and config files are shown read-only. The runnable examples reproduce the key ideas in plain Java. If you need a refresher on what a container build looks like first, read Docker for Java Developers.

JIT versus AOT

flowchart LR
  subgraph JVM["On the JVM"]
    direction LR
    A1["Start JVM"] --> A2["Load and verify<br/>classes"] --> A3["Interpret<br/>bytecode"] --> A4["JIT-compile<br/>hot methods"] --> A5["Peak speed"]
  end
  subgraph NI["Native image"]
    direction LR
    B1["Build time:<br/>analyze + compile"] --> B2["Run executable<br/>(already machine code)"]
  end

The JVM does its analysis and compilation while your program runs; Native Image moves them into the build.

JVM (HotSpot) Native image
Startup seconds for a Spring app tens to a few hundred milliseconds
Memory at idle high (class metadata, JIT, heap) much lower
Peak throughput excellent after warm-up usually a bit lower without profile-guided optimization
Build time seconds minutes, gigabytes of RAM
Dynamic features everything works reflection, proxies, resources need metadata
Debugging and tooling JFR, JMX, agents, hot reload fewer tools (some JFR and heap-dump support exists)
Portability one JAR runs everywhere one executable per OS and CPU architecture

Neither wins in general. Native images shine for scale-to-zero workloads, serverless functions, CLI tools and memory-constrained sidecars. A long-running, CPU-heavy service often performs better on the JVM, and with the JDK's own startup improvements (the AOT cache described in Deploying Java Applications) the gap for ordinary services is shrinking.

The closed-world assumption

To compile ahead of time, Native Image must know every class and method that can ever run. It starts from your main method and follows every call, every field access and every instantiation it can see in the bytecode. This is called reachability analysis (a points-to analysis, to be exact). Whatever it never reaches is simply not put into the executable. That is why the result is small, and also why it is called a closed world: nothing may appear later that the analysis did not see.

The next program models this on a tiny call graph. It computes what is reachable from main, and then shows what happens when code is reached only by a string name, which the analysis cannot read.

Java Reachability analysis on a tiny call graph

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Your own dead code disappears. So does dead code in your dependencies and in the JDK: a program that never touches javax.xml doesn't carry the XML parser. But LegacyExport is the interesting case: it is used, just not in a way the analysis can see.

Reflection, proxies and resources

Anything that finds code or data by a name computed at run time is invisible to the analysis:

  • Reflection: Class.forName("com.acme.Plugin"), getDeclaredMethod("run"), field.set(...). Jackson, Hibernate, JUnit and Spring's dependency injection all use it.
  • Dynamic proxies (java.lang.reflect.Proxy), used for repositories, @Transactional and Feign-style clients.
  • Resources loaded with getResourceAsStream("templates/home.html").
  • Serialization and JNI (calls into native libraries).

Without help, a native image either fails with a ClassNotFoundException or NoSuchMethodException, or, worse, appears to work until a rarely used code path runs in production. The fix is reachability metadata: a JSON file telling the build "keep this class, these methods, those resources". Libraries ship their own under META-INF/native-image/<group>/<artifact>/, and your application adds more. In current GraalVM versions all kinds of metadata live in one file, reachability-metadata.json; older versions used separate reflect-config.json, resource-config.json, proxy-config.json and serialization-config.json files, which you will still see in many projects.

JSON
{
  "reflection": [
    {
      "type": "com.acme.export.CsvExporter",
      "allDeclaredConstructors": true,
      "methods": [ { "name": "export", "parameterTypes": ["java.util.List"] } ]
    }
  ],
  "resources": [
    { "glob": "templates/**" },
    { "glob": "messages*.properties" }
  ]
}

You rarely write this by hand. Three tools produce it:

  1. The tracing agent. Run your application (and ideally your integration tests) on a normal GraalVM JVM with java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image -jar app.jar. The agent records every reflective lookup it observes and writes the metadata files. It only knows what your run exercised, so cover your code paths.
  2. The GraalVM Reachability Metadata Repository. A community-maintained collection of metadata for popular libraries. The Maven and Gradle native plugins download it automatically.
  3. Framework support. Spring, Quarkus and Micronaut generate the metadata for the code they manage (see below).

The next program is a miniature tracing agent. It wraps reflection in a recorder, runs a small "application" that loads exporters by name, and prints the metadata it would need (in a simplified shape; the real file lists each method as an object with name and parameterTypes).

Java A miniature tracing agent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the weakness the real agent shares: only the exporters that actually ran were recorded. If a third exporter is configured in production but never exercised in your run, it is missing from the image. That is why native builds need good tests, as described below.

Native images with Spring Boot

Spring's whole programming model leans on reflection and proxies, so for years Spring and native images were awkward partners. Spring Boot 3 and later solved it with AOT processing. At build time, a Spring AOT step starts the application context far enough to see all bean definitions, conditions and auto-configurations, and then generates plain Java source that creates the beans directly (no classpath scanning, no @Conditional evaluation at startup) plus the reachability metadata for everything Spring itself needs. The generated classes then go through the normal compiler and into the native image.

flowchart TD
  S["Your source + dependencies"] --> C["javac / Maven compile"]
  C --> A["Spring AOT processing<br/>(process-aot)"]
  A --> G["Generated bean factories<br/>+ reachability metadata"]
  G --> N["native-image compiler<br/>(analysis, AOT compile, link)"]
  C --> N
  N --> E["Standalone executable"]

Spring AOT turns runtime decisions (which beans exist, which conditions match) into build-time code, so the closed-world analysis can see it.

A consequence worth knowing: because conditions are evaluated at build time, the set of beans is fixed. A property like spring.profiles.active that changes which beans exist cannot be changed at run time in a native image; only values (ports, URLs, passwords) can. @ConditionalOnProperty on a bean is decided when you build.

Add the GraalVM native build tools through the parent POM profile that Spring Boot already defines, then build:

Terminal
# needs GraalVM (for example via SDKMAN: sdk install java 25-graal) on the machine
./mvnw -Pnative native:compile
./target/library-service            # a ready-to-run executable, no JVM needed

# or build a container image without installing GraalVM, using Cloud Native Buildpacks
./mvnw -Pnative spring-boot:build-image
docker run --rm -p 8080:8080 library-service:1.4.2

When your own code needs reflection that Spring cannot infer, you declare it in Java next to the code, with the RuntimeHints API, rather than hand-editing JSON:

Java
@Configuration
@ImportRuntimeHints(ExporterHints.class)
class ExportConfig { }

class ExporterHints implements RuntimeHintsRegistrar {
    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        hints.reflection().registerType(CsvExporter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS);
        hints.resources().registerPattern("templates/*.html");
    }
}

Two shortcuts cover the most common case, JSON binding. @RegisterReflectionForBinding(BookDto.class) registers a class that Jackson serializes, and for record-based request and response bodies in controllers Spring registers the hints automatically. Spring's testing support helps too: @DisabledInAotMode marks tests that cannot run in AOT mode, and ./mvnw -PnativeTest test runs your JUnit tests inside a native image to catch missing metadata before production does.

Build-time versus run-time initialization

Native Image runs static initializers either while building or when the program starts. By default it initializes your classes at run time (safe but slower to start) and a few JDK classes at build time. With --initialize-at-build-time=com.acme.Constants the static state is computed once and baked into the executable's image heap. That makes startup even faster, but anything captured at build time stays frozen: a random seed, a timestamp, an environment variable or a connection would be the build machine's value, forever.

The following program shows the pitfall in miniature. BUILD_TIME is computed when the class initializes; think of "initialize at build time" as running that line once on the build server and shipping the result.

Java Why build-time initialization freezes values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The practical rule: keep configuration in beans and methods, not in static fields. Spring Boot already follows it, so you only run into this with your own static state or with libraries that need --initialize-at-run-time for classes holding random generators, threads or sockets (the error message from the builder names the class).

Tuning and trade-offs

  • Build speed. native-image -Ob (quick build mode) skips most optimizations and is good for development loops. Release builds use the default -O2-like level; -O3 and profile-guided optimization (--pgo-instrument, then run a realistic workload, then --pgo) are available in Oracle GraalVM and recover much of the JIT's peak throughput.
  • Memory. Native images start with a small heap and use a simpler garbage collector than HotSpot's default, so very allocation-heavy services can be slower. Measure with your workload; set the maximum heap with -Xmx at start-up just like on the JVM.
  • Diagnostics. There is no JIT to attach to, and agents and bytecode tools don't work. Rely on logs, Micrometer metrics and OpenTelemetry (Actuator, Metrics and Observability); build with -g when you need a debugger.
  • Dependencies. Prefer libraries that publish native metadata. A library that generates classes at run time (some bytecode-heavy tools) usually can't work at all.
  • CI. Native builds are slow, so build them in a dedicated pipeline stage, cache Maven dependencies, and run the native test suite there. See the pipeline in Deploying Java Applications.

Don't switch to native "because it is faster" without a reason. Start by measuring: if your service starts in four seconds on the JVM and Kubernetes can roll it out gradually, you may gain nothing. If you scale to zero or run hundreds of small instances, native pays off quickly. Frameworks designed around build-time work, covered next in Quarkus and Micronaut Compared, make the native path smoother than a retrofit does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the "closed-world assumption" mean for a native image?

    Native Image analyzes the program from its entry points at build time and compiles only what it can prove reachable. Code that appears later by name must be declared as metadata.
  2. 2. Your native image fails at run time with ClassNotFoundException for a class you load with Class.forName(name) where name comes from a config file. What is the correct fix?

    The analysis cannot see the string, so it dropped the class. Metadata, produced by the tracing agent, a library or RuntimeHints, tells the build to keep it.
  3. 3. What does Spring Boot's AOT processing do at build time?

    AOT processing turns decisions normally made while the context starts into generated code, which the native-image compiler can analyze. The set of beans is therefore fixed at build time.
  4. 4. A static final field holding System.getenv("DB_URL") is initialized at build time. What happens in production?

    Build-time initialization stores the object in the image heap. Read configuration at run time instead of in static initializers.
  5. 5. Which workload benefits most from a native image?

    Fast startup and low memory are the native image's strengths. Peak throughput, dynamic class generation and agents favor the JVM.

Summary

  • GraalVM Native Image compiles a Java application ahead of time into a standalone executable: millisecond-scale startup and low memory, in exchange for slow builds, per-platform binaries and a stricter model.
  • It works under a closed-world assumption: only code reachable from the entry points at build time is included.
  • Reflection, dynamic proxies, resources and serialization need reachability metadata (reachability-metadata.json), produced by the tracing agent, the metadata repository, frameworks or the RuntimeHints API.
  • Spring Boot AOT generates bean-definition code and hints at build time, so the set of beans is fixed when you build; only values can change at run time.
  • Static state initialized at build time is frozen into the image: read configuration at run time.
  • Test native builds in CI (-PnativeTest) and choose native when startup time and memory matter most; keep the JVM when peak throughput and tooling matter more.

Next: Quarkus and Micronaut Compared looks at two frameworks built around this build-time philosophy from the start.