Sub topic 3
What GraalVM native-image produces
This chapter assumes you know Java 17 or later, can build a Spring Boot project with Maven or Gradle, and understand reflection and dynamic proxies at a conceptual level. It covers what the native-image tool takes as input, what it writes as output, and what that output does and does not contain. Later chapters cover the Spring-specific build steps.
The tool and its place in the build
native-image is a command-line tool that ships with GraalVM. It reads compiled Java bytecode and produces a platform-specific executable. The tool is a separate step that runs after javac. It does not compile .java files. It consumes .class files and JARs.
The input is:
- Your application classes and every library JAR on the classpath.
- The JDK classes your code can reach.
- Optional configuration: reachability metadata and build options.
The output is a single executable file for the operating system and CPU architecture you built on. A Linux x64 build will not run on macOS or on Linux ARM. Because there is no cross-compilation, a CI pipeline that targets several platforms needs one build per platform.
You normally do not call native-image yourself in a Spring Boot project. The Maven or Gradle native plugin assembles the classpath and arguments, then invokes it. Seeing the underlying command helps you read build logs:
native-image -cp target/classes:target/lib/* com.example.demo.DemoApplication -o target/demoThe -cp option is the classpath, the class name is the entry point with a main method, and -o names the output file.
What happens during a build
The build runs in stages. Knowing the order explains most of the build's behavior.
- Static analysis. Starting from the
mainmethod, the tool follows every call it can see and records which classes, methods and fields are reachable. Code that is not reachable is dropped. The next chapter's topic, the closed-world assumption, is the rule that makes this safe. - Build-time initialization. Some classes run their static initializers while the build is running, not when the program starts. The results of that work are stored in the image.
- Heap snapshot. The objects created by build-time initialization are written into the executable as an image heap. At startup the process maps this heap into memory instead of recreating the objects.
- Ahead-of-time compilation. Every reachable method is compiled to machine code.
- Linking. The machine code, the image heap and a small runtime are combined into one executable.
The build is slow and memory-hungry because it analyzes the whole program, including the JDK parts you use and all of your dependencies. A small Spring Boot application commonly takes one to several minutes and several gigabytes of RAM. Larger applications take longer.
What is inside the executable
The executable is not a JAR with a JVM wrapped around it. It contains three things.
| Part | What it holds |
|---|---|
| Machine code | Compiled code for all reachable methods |
| Image heap | Objects and static state created during the build |
| Substrate VM | A small runtime with a garbage collector, thread support and other low-level services |
Substrate VM
Substrate VM is the runtime that gets embedded in the executable. It provides memory management, garbage collection, threads, signal handling and similar services. It is not the HotSpot JVM. The consequences:
- There is no bytecode interpreter and no JIT compiler at runtime. Code that was not compiled at build time cannot be run.
- There is no class loading from files. Classes are fixed at build time.
- The default garbage collector is Serial GC. Other collectors, such as G1, are available in some GraalVM editions and on some platforms, with restrictions.
- Java agents and the debugging and monitoring interfaces of HotSpot do not work the same way. JMX support is limited, and tools such as
jcmdand VisualVM do not attach.
The image heap
Any static field initialized during the build is stored in the image heap. This is why startup is fast: the work is already done. It is also a source of surprises. If a static initializer reads an environment variable, a random number or the system clock during the build, the value baked into the executable is the value from the build machine, not from the machine where the program runs.
Resources
Files on the classpath, such as application.properties or templates, are not included automatically unless they are registered. The tool embeds only the resources that metadata asks for. Spring Boot's build plugin registers the resources it knows about. Your own files need a hint, which a later chapter covers.
What the build leaves out
The tool removes everything it cannot prove is needed. This includes:
- Methods and classes that no reachable code calls.
- Classes that are only used through reflection, unless metadata lists them.
- Resource files that were not registered.
- Dynamic proxy classes that were not declared.
- Classes loaded by name from a string, for example with
Class.forName, unless declared.
Dropping these items keeps the executable small and the startup fast. The cost is that a call that works on the JVM can fail in the native executable. The failure usually appears as a ClassNotFoundException, a NoSuchMethodException, a missing resource, or a reflection error that mentions a missing registration. The usual causes and fixes appear in later chapters.
A small program and its output
You can see all of this without Spring. Save this class as Hello.java:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello from " + System.getProperty("java.vm.name"));
}
}Compile it, then build and run both forms. This needs a GraalVM distribution with native-image on the path:
javac Hello.java
java Hello
native-image Hello
./hellonative-image Hello writes an executable named hello in the current directory, using the lowercased class name. The two runs print different VM names. The JVM run prints the name of the JVM you used. The native run prints a Substrate VM name, which confirms that a different runtime is executing the code.
You can also compare sizes with ls -lh hello. A trivial program produces an executable of several megabytes, because the runtime and the reachable JDK code are included. A Spring Boot application is usually tens of megabytes or more.
Build output and reports
The build prints a summary near the end. It lists how many classes, methods and fields were reachable, how many of them are registered for reflection, and the size of the code area and the image heap. These numbers are useful when you compare builds. A sudden jump in reachable methods after adding a dependency shows that the dependency pulled in more code than you expected.
The tool can also write detailed reports. Build options are passed with -H: for hosted options, and the most useful ones for this purpose are:
--emit build-reportto write an HTML report of what ended up in the executable. Availability depends on the GraalVM version.-H:+PrintClassInitializationto list when each class is initialized.--verboseto print more of the build's internal steps.
Option names change between GraalVM releases, so check native-image --help-extra for your installed version.
Fallback images and the no-fallback rule
In older releases, if the analysis found something it could not handle, the tool silently produced a fallback image. A fallback image is a small launcher that needs a full JVM to run the application. It starts as an executable but gives none of the benefits of native compilation. Current releases do not create fallback images by default and fail the build instead. Spring Boot's native plugins also set the equivalent option. If you see a message about a fallback image, treat it as a build failure to fix, not as a working native build.
Limits you should know about
- Platform-bound output. The executable runs only on the platform it was built for. Build in a container or on a matching CI runner for your target.
- Dynamic features. Reflection, resource loading, serialization, JNI and dynamic proxies all need registration. Runtime bytecode generation, such as defining classes with
ClassLoader.defineClass, is not supported in general. - Peak throughput. The JVM's JIT can use runtime profiling to optimize hot code. Ahead-of-time code has no such profile unless you supply one with profile-guided optimization, which is available only in some GraalVM editions. For long-running, CPU-heavy work the JVM can be faster after warm-up.
- Tooling. Heap dumps, profilers and agents that depend on HotSpot behave differently or are unavailable.
Exercise
A static field in a library class is initialized with System.currentTimeMillis(). The class is initialized at build time. What value does the native executable see at runtime, and why?
Show answer
It sees the timestamp from the build, not from the program start. Build-time initialization runs the static initializer once during the build, and the resulting object is stored in the image heap. At startup the executable maps that heap and does not run the initializer again.
Exercise
Your application calls Class.forName("com.example.PluginA") with a name read from a config file. It works on the JVM but throws ClassNotFoundException in the native executable. What is the likely cause?
Show answer
The static analysis could not see that PluginA is used, because the name is only a string. The class was removed from the executable. You must register it as reachable through reflection metadata or a runtime hint so the build keeps it.
Exercise
Name two things the executable produced by native-image contains that a JAR file does not, and one thing it lacks that a JVM process has.
Show answer
It contains machine code compiled ahead of time and an image heap of pre-initialized objects, along with the Substrate VM runtime. It lacks a bytecode interpreter and JIT compiler, so it cannot run code that was not compiled at build time.