Sub topic 12
Diagnosing common failures
This chapter assumes you can build a native executable with native-image, know what reachability metadata is, and have used the tracing agent at least once. It also assumes you know the difference between build-time and run-time class initialization. Here you will learn to sort a failure into a category, find the cause, and apply the smallest fix.
Three places a native image can fail
A native image has three stages, and each fails in its own way:
- Build time.
native-imagestops with an error, or ends with a warning about a fallback image. - Start time. The executable crashes or misbehaves as soon as it starts, usually because of initialization order or state captured during the build.
- Run time. The program starts, then fails on one code path that uses reflection, resources, proxies or serialization.
Decide which stage you are in before you change anything. The same exception name can come from different causes in different stages.
Build-time failures
Toolchain problems
A message such as Default native-compiler executable 'cc' not found means the C toolchain is missing. Native Image uses a system compiler and linker for the final step. On Linux, install gcc, the C library headers and the zlib development package. On Windows, use a shell with the Visual Studio build tools on its path. Static linking (--static) needs static versions of the libraries. A linker error like cannot find -lz usually means the static zlib package is missing.
Build runs out of memory
The builder is a Java program with its own heap, and large applications need a lot of it. Pass options to the builder JVM with the -J prefix:
native-image -J-Xmx12g -jar app.jar -o appClose other memory-hungry processes, or build in CI with enough RAM. For quick feedback while developing, add -Ob, which lowers the optimization level so the build finishes sooner. Do not use it for the binary you benchmark.
Fallback images
Older releases could silently produce a fallback image when static analysis found a problem. This is a launcher that still needs a JVM. If your executable prints a message about needing a Java runtime, you got one. Pass --no-fallback so the build fails instead and shows you the real error:
native-image --no-fallback -jar app.jar -o appInitialization errors
The most common build error reports a class that was initialized during the build when it must be initialized at run time. Typical messages are:
Classes that should be initialized at run time got initialized during image buildingDetected a started Thread in the image heapDetected an instance of Random/SplittableRandom class in the image heap
All of these mean the build ran a static initializer and saved its result in the image. The saved object cannot be used safely at run time. Typical cases are a thread, an open file or socket, a random number generator seeded at build time, or a timestamp.
Here is a class that causes the problem when you request build-time initialization:
public class Config {
static final long STARTED = System.currentTimeMillis();
static final String HOME = System.getenv("APP_HOME");
public static void main(String[] args) {
System.out.println("Started at " + STARTED + ", home=" + HOME);
}
}javac Config.java
native-image --initialize-at-build-time=Config Config
APP_HOME=/opt/app ./configBoth values were computed while the image was being built. STARTED is the build time, and HOME is whatever APP_HOME was in the build environment, possibly null. The program runs without error and prints the wrong answers. Of the three kinds of failure, this one is the hardest to notice.
Ask the builder to explain why a class was initialized:
native-image --trace-class-initialization=Config ConfigThe output lists the call chain that triggered initialization. If you find the cause, you have two options:
- Initialize the class at run time with
--initialize-at-run-time=com.example.Config. This is the usual fix. - Change the code so the static initializer holds no environment-dependent state. Read it lazily inside a method instead.
Initialization options apply to a class and, for a package name, to its subpackages. Many libraries ship their own settings in META-INF/native-image/.../native-image.properties, so check there before adding flags for a library class. Your own flags can conflict with them.
Reading the full error
Some builder errors show only the last exception. Add -H:+ReportExceptionStackTraces to see full stack traces. Use --verbose for more detail on the build phases.
Start-time failures
If the image starts and exits immediately, check these causes in order:
- Static state captured at build time, as in the
Configexample above. - A missing resource that the startup code reads, such as a configuration file. See the next section.
- A native library that the application loads through JNI but which is absent on the target machine.
- A mismatch between build and target platform. An executable built on a glibc system will not run on a system with an older glibc. A statically linked or musl-based image avoids this. See the packaging chapter.
Run the executable from a terminal, not a service manager, so you see the first lines of error output.
Run-time failures from missing metadata
Static analysis cannot see names that are computed at run time. When code asks for a class, resource or proxy that the image does not contain, the failure appears only on that code path. That is why a build can pass and the program can still fail in production.
| Symptom | Cause | Fix |
|---|---|---|
| `ClassNotFoundException` from `Class.forName` | Class not registered for reflection | Add an entry to `reflect-config.json` |
| `NoSuchMethodException` or `NoSuchFieldException` | Class is registered, but this member is not | Register the constructor, method or field |
| `getResourceAsStream` returns `null` | Resource not included in the image | Add a pattern to `resource-config.json` |
| Error creating a dynamic proxy | Interface list not registered | Add it to `proxy-config.json` |
| Error while serializing or deserializing | Class not registered for serialization | Add it to `serialization-config.json` |
| A `MissingReflectionRegistrationError` or similar message | The runtime reports the missing registration by name | Register exactly what the message names |
The last row is the best case. Newer releases can throw errors that name the missing element, which saves guessing. Read the message and register what it names.
Reflection
The Reflective program from earlier loads com.example.Greeter by name. Without metadata, the executable throws ClassNotFoundException even though the class was on the classpath at build time. The registration is:
[
{
"name": "com.example.Greeter",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]Place it in META-INF/native-image/ inside your resources. For a project layout, use a subdirectory named after your group and artifact, such as META-INF/native-image/com.example/app/reflect-config.json.
Resources
Resources are not copied into the image unless you ask for them. This code works on a JVM and fails in a native image:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Messages {
public static void main(String[] args) throws IOException {
try (InputStream in = Messages.class.getResourceAsStream("/messages.properties")) {
if (in == null) {
throw new IllegalStateException("messages.properties not found");
}
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("greeting"));
}
}
}Include the file with resource-config.json:
{
"resources": {
"includes": [
{ "pattern": "\\Qmessages.properties\\E" }
]
}
}Patterns are regular expressions. \Q...\E quotes the file name so the dot is literal. A pattern like .*\\.properties$ includes every properties file, at the cost of a larger image.
Using the agent without gaps
The tracing agent records only what the run actually did. If a code path never executed, the agent writes nothing for it, and the failure comes back in production. Follow these rules:
- Exercise every feature, including error paths, with a test suite or a scripted session.
- Run the agent several times, one per scenario, and merge results with
config-merge-dirinstead ofconfig-output-dir, which overwrites. - Review the generated files before you commit them. They can include entries for test-only classes.
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image -jar app.jarRebuild after each change to the metadata, then repeat the failing scenario against the native executable, not the JVM.
Debugging the running executable
A native executable has no JIT and no JVM tools such as jstack, so use these instead:
- Pass memory options at launch, for example
./app -Xmx512m. The runtime accepts a maximum heap setting, and-XX:+PrintGCprints collections, which helps when you suspect memory pressure. - Build with
-gto include debug information, then step through the code withgdb. - Log liberally. Stack traces in native images are often shorter than on the JVM, but they still show the failing call.
- Reproduce the problem on the JVM first. If it fails there too, the cause is your code, not Native Image.
A short checklist
- Note the stage: build, start or one code path.
- Read the first error line. Do not skip to the last.
- For initialization problems, use
--trace-class-initializationand move the class to run time. - For missing-name problems, register the name, either by hand or with the agent.
- Rebuild, and test the native executable on the exact scenario that failed.
Exercise
A Maven build with the native profile succeeds. The executable starts and works, but when a user opens the "Export" feature it throws ClassNotFoundException for a class that exists in your JAR and is loaded with Class.forName. The JVM version works. What is the cause, and what two steps fix it reliably?
Show answer
The class name is computed at run time, so static analysis did not see it, and the image has no reflection registration for it. The build passed because the failure only appears on the Export code path. Fix it by (1) running the application on a GraalVM JVM with the tracing agent (using config-merge-dir) while exercising the Export feature, or adding the class by hand to reflect-config.json under META-INF/native-image; and (2) rebuilding the image and testing the Export feature on the native executable.
Exercise
A class reads System.getenv("REGION") in a static initializer. After building with --initialize-at-build-time for that class, the executable always reports the REGION of the build machine. Why does it happen, how can you confirm which class initialization caused it, and what is the fix?
Show answer
The static initializer ran during the image build, and the resulting value was stored in the image heap, so the run-time environment is never read. Confirm with --trace-class-initialization=<class name>, which prints what triggered initialization. Fix it by removing build-time initialization for the class and using --initialize-at-run-time=<class name>, or by reading the variable lazily inside a method.