Sub topic 2
The closed-world assumption
This chapter assumes you know Spring Boot basics (beans, auto-configuration, properties), have built a project with Maven or Gradle, and understand Java reflection and dynamic proxies at a conceptual level. It explains the rule that shapes almost every native-image problem you will meet: the compiler must know everything your program can do before the program runs.
What the assumption says
On a JVM, a class loader can load any class at any time. Your code can call Class.forName("com.example.Plugin") with a string read from a file, and the JVM finds the class on the classpath and loads it. The set of classes that will run is open until the program ends.
GraalVM Native Image works differently. At build time, its static analysis starts from the application's entry point and finds every class, method, and field that can be reached. Only reachable code goes into the executable. Code that the analysis does not reach is removed. Nothing can be loaded or generated afterwards, because the executable has no class loader that reads .class files and no JIT compiler to produce new code.
This is the closed-world assumption: the set of code that can run is fixed at build time, and the build must be able to see all of it.
How the analysis works
The analysis is a fixed-point computation. It starts with the entry point (main) and marks it reachable. It then looks at every method that is reachable, finds the methods it calls and the types it instantiates, and marks those reachable too. It repeats until no new elements are found.
Three consequences follow.
- Direct calls are easy.
new OrderService().place(order)names its targets in the bytecode, so the analysis follows it. - Virtual calls are approximated. For
list.add(x), the analysis considers the implementations of the type that it has seen instantiated. - Dynamic features are invisible. If the target of an operation is computed from a string or a runtime value, the analysis cannot follow it.
The third point is where problems arise. Spring Boot applications use dynamic features heavily, which is why Spring adds its own build-time step. That step is covered in a later chapter.
What breaks under a closed world
Four Java features depend on an open world. In each case the analysis cannot see the target, so you must declare it.
| Feature | Why the analysis cannot see it | What happens without metadata |
|---|---|---|
| Reflection | The class or member name is a string or a runtime value | The class may be removed, or its members are not accessible, and the call fails at runtime |
| Resources | Files on the classpath are located by name at runtime | The file is not packaged, and lookup returns `null` |
| Dynamic proxies | Proxy classes are generated at runtime from interface lists | The proxy class does not exist in the executable |
| JNI and serialization | Native code or the serialization machinery looks up members by name | Lookups fail at runtime |
Other runtime class generation falls under the same limit. Libraries that generate bytecode when the application runs (for example with ByteBuddy or CGLIB at runtime) cannot do so in a native executable, because there is no JVM to load the new class.
Reflection
Here is a method that hides its target from the analysis:
public class Loader {
public static Object create(String className) throws Exception {
Class<?> type = Class.forName(className);
return type.getDeclaredConstructor().newInstance();
}
public static void main(String[] args) throws Exception {
Object value = create(args.length > 0 ? args[0] : "java.lang.StringBuilder");
System.out.println(value.getClass().getName());
}
}The class name arrives as an argument. The analysis cannot know which classes the program will ask for. If a class is not registered for reflection, the native executable throws an exception such as ClassNotFoundException or NoSuchMethodException. The same program works on the JVM, because the JVM can look the class up whenever it is asked.
Constant arguments are a partial exception. When the argument is a compile-time constant, such as Class.forName("java.lang.StringBuilder"), the analysis can often resolve it by itself and register the class. Rely on this only as a bonus. The args[0] path above is not resolvable.
Resources
A call like getResourceAsStream("templates/greeting.txt") works on the JVM because the file sits on the classpath. In a native executable there is no classpath of files. A resource is included only if a configuration entry says it should be. If you forget, the lookup returns null, and the usual symptom is a NullPointerException further along.
Dynamic proxies
java.lang.reflect.Proxy builds a class at runtime from a list of interfaces. The native build can include a proxy class only if it knows the exact interface list in advance. This matters for Spring features that wrap beans in proxies, such as @Transactional with JDK proxies, and for libraries that proxy interfaces, such as declarative HTTP clients.
Why the assumption is worth its cost
The closed world is what makes the benefits possible.
- Startup is fast, because the work of loading, linking, and initializing classes is mostly done at build time.
- Memory use is low, because unreachable code is gone and there is no JIT compiler or profile data in memory.
- The executable is self-contained, so it needs no JVM at run time.
These come from the same restriction. A tool that must support every possible dynamic action cannot remove anything. A tool that knows the full set of actions can discard the rest.
Build time versus run time
The closed-world assumption splits an application's life into two phases, and some things you are used to doing at run time move to build time.
- Class initialization can run during the build. GraalVM can execute static initializers at build time and store the resulting objects in the executable's image heap. By default, application classes are initialized at run time, and the build initializes only those it can prove safe or that were explicitly configured. Spring Boot's build tooling configures some of this for you.
- The classpath is fixed. Adding a JAR to the runtime does nothing.
- Anything computed from the environment during build time stays in the executable. A value captured in a static field during build-time initialization (a timestamp, a host name, a random seed) is the same on every run.
The last point is a common source of bugs. A static final Random seeded during build-time initialization produces the same sequence in every process. Prefer run-time initialization for anything that depends on the environment.
import java.time.Instant;
public class Stamp {
// Safe on a JVM. If this class were initialized at build time,
// the timestamp would be frozen into the executable.
static final Instant STARTED = Instant.now();
public static void main(String[] args) {
System.out.println("started at " + STARTED);
}
}Native Image initializes this class at run time by default, so each run prints its own time. The example shows what to watch for if you ever configure the class for build-time initialization.
Closed world and Spring
A Spring application is built on dynamic behavior: component scanning reads the classpath, auto-configuration evaluates conditions, and the container instantiates beans by reflection. Run unchanged, this code would hit every limit described above.
Spring Boot 3 handles this with Spring AOT processing. During the build, Spring runs the application's setup logic once, records the result, and generates plain Java source code that creates the beans directly. It also emits hints, which are the metadata the closed-world analysis needs. After this step, most of the dynamic work is already resolved before Native Image starts its analysis.
The consequence for you is that the closed world applies to your code and your libraries, and Spring covers its own part. You are responsible for the dynamic features that you add yourself, such as a Class.forName call, a resource lookup by name, or a library that Spring does not know about.
Common mistakes
- Assuming that code which runs on the JVM will run native. The JVM hides gaps that the native build exposes. Test the native executable, not only the JAR.
- Reading a missing reflection registration as a code bug. The usual symptoms (
ClassNotFoundException,NoSuchMethodException, anullresource) point to missing metadata. - Adding runtime plugins or loading classes from external directories. A closed world cannot load them.
- Capturing environment values in build-time initialized state.
Where this leads
The closed-world assumption explains the rest of the tutorial. The native-image tool performs the analysis. Spring AOT removes most of the dynamic work in advance. Reachability metadata and runtime hints cover whatever is left, and the tracing agent helps you find those leftovers. Later chapters take each of these in turn.
Exercise
A Spring Boot application works when run with java -jar but fails in its native executable with NoSuchMethodException for a class named in a configuration file and loaded with Class.forName. Why does the native build not detect the problem, and what kind of fix is needed?
Show answer
The class name is read from a file at run time, so static analysis cannot see which class will be requested. The build succeeds, and the class or its constructor is missing or inaccessible at run time. The fix is to declare the class for reflection, for example with a RuntimeHintsRegistrar or a reachability metadata file, with the constructor access the code uses. The code itself does not need to change.
Exercise
Name two benefits of the closed-world assumption and the restriction each one depends on.
Show answer
Fast startup depends on the fact that loading and initialization work is done at build time, which requires the set of classes to be fixed in advance. Low memory use depends on removing unreachable code and omitting the JIT compiler, which requires the analysis to know what can run. Both rely on the executable being unable to load or generate new code at run time.