Sub topic 3
The Closed-World Assumption and What Gets Included
This chapter assumes you can build a native executable with native-image, as in the earlier chapter, and that you know how the JVM loads classes lazily. It explains how Native Image decides which classes, methods and fields go into the executable. Most surprises with native images come from that decision.
Open world versus closed world
A JVM works in an open world. At any moment it can load a class that did not exist when the program started. It can read a class name from a file, fetch bytes from the network, or generate a class at run time. The JIT compiler copes with this by compiling optimistically and discarding code when an assumption breaks.
Native Image works in a closed world. Before it emits any machine code, it assumes it can see every piece of code the program will ever run. Anything it cannot see at build time does not exist at run time.
| Aspect | JVM (open world) | Native Image (closed world) |
|---|---|---|
| Class loading | Any class on the classpath, at any time | Only classes found at build time |
| Unused classes | Present in JARs, loaded only if used | Removed from the executable |
| Generating bytecode at run time | Supported | Not supported |
| Reflection by name | Works for any class | Works only for registered elements |
| Optimization basis | Run-time profile, with deoptimization | Whole-program analysis at build time |
The trade is deliberate. A closed world lets the compiler remove code, resolve virtual calls and pre-initialize data. In return, the program gives up dynamic behavior the compiler cannot predict.
How the static analysis works
Native Image runs a points-to analysis, a whole-program analysis that tracks which types can flow to which variables. The analysis does not look at your whole classpath. It starts from a small set of entry points and expands outward.
- The entry points are the
mainmethod, plus methods the build configuration marks as roots, such as those registered in metadata. - The analysis processes every method it has found. For each method, it finds the methods it calls, the types it instantiates, and the fields it reads or writes.
- Each newly found element joins the reachable set, and the analysis processes it too.
- The analysis repeats until a pass finds nothing new. This stable state is called a fixed point.
Only elements in the final reachable set are compiled and written to the executable.
What "reachable" means for each kind of element
- Methods: A method is reachable if some reachable code can call it. The analysis follows static calls, constructor calls and virtual calls.
- Types: A type is reachable if reachable code mentions it. A type is instantiated if reachable code creates an object of that type. The distinction matters for virtual calls.
- Fields: A field is reachable if reachable code reads or writes it. Fields that are never read can be removed even though their class stays.
Virtual calls and type flow
Consider an interface with two implementations:
interface Shape {
double area();
}
class Circle implements Shape {
public double area() { return Math.PI; }
}
class Square implements Shape {
public double area() { return 1.0; }
}
public class Shapes {
public static void main(String[] args) {
Shape s = new Circle();
System.out.println(s.area());
}
}The analysis sees that only Circle is ever instantiated. Square is never created, so Square.area() is not compiled, even though Square implements the interface that main calls. The call s.area() has a single possible target, so the compiler can turn it into a direct call and possibly inline it. A JVM can reach the same result only by profiling, and it must be ready to undo the optimization.
A closed-world experiment
The following program makes the closed world visible. It loads a class by a name chosen at run time. Save the first file as com/example/Greeter.java:
package com.example;
public class Greeter {
@Override
public String toString() {
return "Hello from Greeter";
}
}Save the second file as com/example/Main.java. Nothing in it mentions Greeter directly:
package com.example;
public class Main {
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "com.example.Greeter";
try {
Class<?> c = Class.forName(name);
System.out.println("Found " + c.getName());
} catch (ClassNotFoundException e) {
System.out.println("Missing " + name);
}
}
}Compile and run it on the JVM, then build and run a native image:
javac -d out com/example/Greeter.java com/example/Main.java
java -cp out com.example.Main
native-image -cp out com.example.Main -o demo
./demoThe JVM prints Found com.example.Greeter. The native executable prints Missing com.example.Greeter. Greeter was on the classpath at build time, but no reachable code referred to it. The analysis could not know that a string at run time would name it, so the class was left out.
What the closed world excludes
Several JVM features cannot work when the set of code is fixed at build time:
- Defining classes at run time. Calls such as
ClassLoader.defineClass, and libraries that generate bytecode when the application runs, have no bytecode interpreter or JIT to run the result. Frameworks that depend on this need a build-time alternative. - Loading classes from arbitrary locations. A custom class loader can't bring in classes that were not part of the build.
- JVM tool interfaces. Java agents, JVMTI and similar mechanisms that assume a running JVM are not available in the same form.
- Unregistered dynamic access. Reflection, JNI lookups, dynamic proxies, resource loading and serialization all reach elements by name or by shape. The analysis cannot see them unless they are registered. Reflection is the first of these, and the next chapter covers it.
Code that fails this way often compiles and passes tests on the JVM. The failure appears only when the native executable runs.
Reading what the analysis kept
At the end of a build, native-image prints a summary of how many types, fields and methods it found reachable, often as a count against the total it examined. Treat these numbers as a first measure of your closed world. A small hello-world program still contains thousands of reachable methods, because the JDK classes behind System.out and string handling come along.
You can learn more from the build output:
- Large reachable counts after adding one dependency show that the dependency pulls in a lot of code.
- Recent versions can write a build report. Pass
--emit build-reportto get an HTML report of the image's contents by package and class. Check that your GraalVM version supports it. - Build options that print the analysis call tree can show why a given method is reachable. Their names have changed between releases, so look up the options for your version with
native-image --help-extra.
Consequences for image size and behavior
Reachability drives several things you will care about later:
- Image size. Every reachable method is compiled to machine code. Removing unused dependencies and avoiding broad static references shrinks the executable.
- Start-up. The image heap, which holds objects created during build-time initialization, also counts as reachable. Class initialization is a separate topic later in this tutorial, and the analysis interacts with it, because a static initializer that runs at build time can change what the analysis sees.
- Predictable failures. An element missing from the image fails at the point of use, often with
ClassNotFoundException,NoSuchMethodExceptionorMissingReflectionRegistrationError. The error comes from the closed world, not from a corrupt build. - Over-approximation. The analysis is conservative. If it cannot prove a method is unreachable, it keeps it. A native image can therefore contain code that never runs, but it should never lack code that does run, as long as the metadata is complete.
Common mistakes
- Assuming the classpath is the image. Having a class on the classpath does not include it. Only reachable code is included.
- Blaming the build when a reflective lookup fails. The build did what it should. The element was not registered, so the analysis never kept it.
- Using broad registration to hide the problem. Registering whole packages for reflection works but keeps a lot of code and grows the image. Register what you need.
- Ignoring dependency weight. A library with many static entry points can pull large parts of itself into the image. Check the reachable counts when you add one.
Exercise
In the Shape example, Square implements Shape, and main calls s.area() on a Shape. Why does the native image not contain Square.area()?
Show answer
The analysis tracks which types are actually instantiated. Only Circle is ever created, so the call s.area() can reach only Circle.area(). Square is never instantiated, so Square.area() is unreachable and is left out. The call can also be turned into a direct call.
Exercise
A program calls Class.forName(System.getProperty("plugin")). It works on the JVM with -Dplugin=com.acme.Plugin, but the native executable throws ClassNotFoundException. Explain why, and name what you must provide.
Show answer
The class name is known only at run time, so the static analysis cannot see that com.acme.Plugin is needed. The class is unreachable and is left out of the image. You must supply reachability metadata that registers com.acme.Plugin for reflection, either by hand or by running the tracing agent, so the class is kept in the image.