Sub topic 2
Building and Running Your First Native Image
This chapter assumes you can compile and run Java from the command line, know what a JAR and the classpath are, and have a rough idea of what the JVM and its JIT compiler do. You will install the tooling, build two native executables, and look at what the build produces. Reflection and other dynamic features come in later chapters.
What you need installed
Native Image is a tool that ships with GraalVM and with Oracle GraalVM distributions. It turns Java bytecode into a platform-specific executable. You need:
- A GraalVM JDK that includes the
native-imagetool. Check withnative-image --version. - A C toolchain for linking. On Linux this is
gccand the zlib development headers. On macOS it is the Xcode command-line tools. On Windows it is the Visual Studio Build Tools.
The JAVA_HOME variable should point at the GraalVM JDK, and its bin directory should come first on PATH. If java -version does not mention GraalVM, javac and native-image may come from different JDKs, and the build can fail with class-version errors.
Compile first, then build the image
Native Image does not read source code. It reads compiled bytecode, so you always run javac (or your build tool) first. Start with a minimal program.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, native image!");
}
}Compile it, build the image, and run it.
javac Hello.java
native-image Hello
./helloThe native-image command takes a main class name, like java does. It writes an executable named after the class in lowercase, here hello, into the current directory. Running ./hello does not start a JVM. The program prints its message directly.
On a typical laptop this build takes tens of seconds and uses several gigabytes of memory. That cost is expected. The tool analyzes your whole program, plus the parts of the JDK it uses, and compiles all of it to machine code.
What happens during the build
The build runs in stages. Knowing them helps you read the build output and later diagnose failures.
- Static analysis. Starting from
main, the tool finds every class, method and field that the program can reach. Anything it cannot reach is left out. The next chapter covers why this works and where it breaks. - Initialization and heap snapshot. Some classes run their static initializers during the build. The objects they create are written into the executable as a pre-built heap, called the image heap.
- Compilation. The reachable methods are compiled ahead of time to machine code.
- Linking. The compiled code, the image heap and a small runtime are linked into one executable.
The runtime in step 4 is called Substrate VM. It provides garbage collection, thread support and other services that the executable needs. It is not a JVM. It cannot load new classes from bytecode at run time.
Reading the build output
The build prints a summary. Exact numbers vary by version and machine, but the shape is stable. Look for these parts:
- Reachable counts. Lines such as "types, fields, and methods registered for reflection" and "reachable types" show how much of your program and the JDK ended up in the image.
- Image breakdown. The code area, the image heap, and other sections add up to the file size. A hello-world image is usually a few megabytes.
- Garbage collector and build memory. The summary names the collector in use and the peak memory the build consumed.
- Build time. Shown at the end, often split into analysis and compilation phases.
Run ls -lh hello to see the file size. Compare it to java -version startup on the same machine with time:
time ./hello
time java HelloThe native executable normally starts in a few milliseconds. The JVM run takes longer because it has to start the VM, load classes and begin interpreting before any JIT compilation happens. This difference is the main reason people use Native Image. Later chapters weigh it against peak throughput.
Building from a JAR
Real applications are packaged as JARs. If a JAR has a Main-Class entry in its manifest, you can build directly from it.
native-image -jar app.jar -o appThe -jar option reads the main class from the manifest and puts the JAR on the analysis classpath. The -o option sets the output file name, so you get ./app instead of a name derived from the manifest.
If your application has dependencies, an ordinary thin JAR will not work, because the dependencies are not inside it. You have two options:
- Build a fat JAR that contains the dependencies, then use
-jar. - Pass a classpath explicitly and name the main class:
native-image -cp "app.jar:lib/*" com.example.Main -o app. On Windows the separator is;.
The -cp form also lets you name any class with a main method, which is useful for building several tools from one codebase.
Common build options
A few options come up from the first day.
| Option | Effect |
|---|---|
| `-o name` | Sets the output file name. |
| `-cp path` | Sets the classpath used for analysis. |
| `-jar file.jar` | Builds from an executable JAR. |
| `--no-fallback` | Fails the build instead of producing a fallback image. |
| `-Ob` | Quick build mode for development. It compiles faster and produces slower code. |
| `-O3` | Uses more optimizations for the final build, at the cost of a longer build. |
| `-H:+ReportExceptionStackTraces` | Prints full stack traces for build errors. |
| `--verbose` | Shows the full underlying command. |
Option names change between GraalVM releases, so check native-image --help and native-image --help-extra for your version.
What does not work the same way
A native executable is a closed program. Several things you rely on in a JVM behave differently:
- Class loading by name.
Class.forNamewith a name only known at run time fails unless you registered that class. The next chapters explain this. - Dynamic bytecode. You cannot generate and load new classes at run time with a custom class loader.
- JVM tooling.
jcmd, JMX-based tools and the standard Java agents do not attach in the usual way. GraalVM provides its own monitoring options, for example through the--enable-monitoringbuild flag. - Default behavior at startup. Static initializers may have run during the build, not when the program starts. This matters when a static field holds a timestamp, a random seed or an environment value.
Here is the last point as a concrete case. This class computes a value in a static field.
public class Stamp {
static final long BUILT = System.currentTimeMillis();
public static void main(String[] args) {
System.out.println(BUILT);
}
}On a JVM, BUILT is set when the class first loads, each time you start the program. In a native image, a class initialized at build time keeps the value it had during the build. By default Native Image initializes application classes at run time, so this example prints a fresh value. Many JDK classes and library classes are initialized at build time, though, and the chapter on class initialization covers how to control this.
A first workflow that works
Use this loop while you are learning.
- Run the program on the JVM first and confirm it works.
- Build with
-Oband--no-fallbackfor fast feedback. - Run the executable and compare its output with the JVM run.
- Fix any failures, which usually involve reflection, resources or initialization.
- Do a final build without
-Ob, and optionally with-O3, before measuring performance.
Always compare behavior before you compare speed. A native image that starts quickly but prints different output is not a successful build.
Check your understanding
Exercise
You run javac Hello.java and then native-image Hello. Name the file that is produced, and explain why running it does not need a JVM.
Show answer
The tool produces an executable named hello (the lowercase class name) in the current directory. It does not need a JVM because the reachable code has been compiled to machine code ahead of time and linked together with Substrate VM, a small runtime that provides garbage collection and threads. No bytecode is loaded or interpreted at run time.
Exercise
A colleague builds native-image -jar app.jar -o app on a Linux x64 machine and sends you the app file to run on macOS. Will it work? What should they do instead?
Show answer
It will not work. A native executable targets the operating system and CPU architecture where it was built. They should build on macOS (or on a machine with the matching platform), or build separately for each target platform in a CI pipeline.
Exercise
Your application has its code in app.jar and a library in lib/util.jar. The main class is com.example.Main. Write a native-image command that builds an executable called app, and say why -jar app.jar alone may fail.
Show answer
native-image -cp "app.jar:lib/*" com.example.Main -o app. Using -jar app.jar alone may fail because a thin JAR does not contain its dependencies, so the analysis cannot find the library classes unless they are on the classpath or bundled in a fat JAR.