Sub topic 7
Class initialization at build time and at run time
This chapter assumes you can build a native executable with native-image and that you know what a Java static initializer is. You should also know that the closed-world analysis decides which classes end up in the image. Here you will learn when a class's static initializer runs in a native image, how that choice changes program behavior, and how to control it.
Why initialization timing matters
On a JVM, a class is initialized lazily. The static initializer and static field assignments run the first time the class is used, and that always happens while the program runs.
Native Image adds a second option. A class can be initialized while the image is being built, inside the builder process. The resulting static field values are then saved in the image, in a region called the image heap. When the executable starts, those objects are already there and the initializer does not run again.
This is good for startup time, because less work happens at launch. It is risky because the builder's environment is frozen into your program. Time stamps, random numbers, environment variables, system properties and file contents read during initialization all become constants.
The default behavior
Since GraalVM 22, most application classes are initialized at run time by default. This keeps the behavior close to a normal JVM. Two things move work to build time anyway:
- Many JDK classes are initialized at build time. The JDK's own build configuration marks them safe.
- The builder can prove that some classes are safe to initialize early. A class with only simple constant assignments and no side effects qualifies. You get the speedup without a change in behavior.
For everything else, you decide explicitly with two command-line options.
| Option | Effect |
|---|---|
| `--initialize-at-build-time=a.b.C` | Run the static initializer of `C` during the build and save the results in the image. |
| `--initialize-at-run-time=a.b.C` | Delay the initializer until the executable first uses `C`. |
You can pass a fully qualified class name or a package name. A package name also covers its subpackages. Separate multiple entries with commas.
A worked example: a frozen time stamp
The following two classes show the difference. BuildStamp records the time at which its static initializer ran. Main prints that time.
public class BuildStamp {
static final long STAMP = System.currentTimeMillis();
static {
System.out.println("BuildStamp initialized");
}
static long stamp() {
return STAMP;
}
}public class Main {
public static void main(String[] args) {
System.out.println("main started");
System.out.println("stamp = " + BuildStamp.stamp());
}
}Compile both classes and build two images from them. The first uses the default. The second asks for build-time initialization of BuildStamp.
javac BuildStamp.java Main.java
native-image Main -o main-runtime
native-image --initialize-at-build-time=BuildStamp Main -o main-buildRun each executable twice.
./main-runtime
./main-runtime
./main-build
./main-buildYou should see the following behavior:
main-runtimeprintsmain startedfirst. It then printsBuildStamp initializedwhenBuildStamp.stamp()is first called. Thestampvalue is different on each run, because the initializer runs every time the program starts.main-builddoes not printBuildStamp initializedat all when it runs. That message appeared in the output of thenative-imagebuild instead. Thestampvalue is identical on every run, because it is the time the build happened.
The second result is a bug if you wanted the current time, and an optimization if the value was meant to be a constant. The language and the compiler cannot tell which you meant, so you have to.
What gets frozen
Build-time initialization saves the state of static fields. It does not save the state of the builder process as a whole. The following table lists the common ways this goes wrong.
| Code in a static initializer | Effect when initialized at build time |
|---|---|
| `System.currentTimeMillis()`, `Instant.now()` | The build time becomes a constant. |
| `new Random()`, `UUID.randomUUID()` | The same "random" values appear in every run. Seeds are shared by all users of the image. |
| `System.getenv(...)`, `System.getProperty(...)` | The values come from the build machine, not the machine that runs the program. |
| Reading a file or opening a socket | The file contents are baked in, or the build fails because the open handle cannot be stored. |
| Starting a thread | The build fails, because threads cannot be part of the image heap. |
Random number generators deserve extra care. Native Image checks for java.util.Random and SplittableRandom instances that are reachable from the image heap, because sharing their seed would be a security problem. The builder reports an error rather than silently baking one in. Initialize classes that create generators at run time.
Constraints between related classes
Initialization choices have to be consistent across a class hierarchy, because initializing a class also initializes related types.
- Initializing a class initializes its superclass first. If a class is initialized at build time, its superclass must be too. Choosing build time for a subclass therefore pulls in the superclass.
- An interface with default methods is initialized together with the classes that implement it. This ties the interface to its implementations.
- A class initialized at run time forces nothing on its superclass. The reverse rule applies to the subclasses of a run-time class: they cannot be initialized at build time, because that would initialize the run-time superclass.
When the builder finds a conflict, it stops with an error that names the classes involved. Fix it by moving the whole group to the same side.
Finding out why a class was initialized
A builder error sometimes says that a class was initialized at build time when it should not have been. Ask the builder to trace the cause with --trace-class-initialization.
native-image --trace-class-initialization=BuildStamp MainThe builder prints the chain of calls that triggered the initialization, starting from the cause. Often the culprit is not your class. Some other class that is initialized at build time touches yours in its own static initializer, and that pulls yours in. The trace shows the first link in the chain, and that is the class you need to change.
A second option, --trace-object-instantiation=a.b.C, shows where an instance of a given class was created at build time. Use it when an object appears in the image heap that should not be there.
Setting options permanently with native-image.properties
Typing options on the command line does not work for a library. The projects that use it would have to repeat them. A library can instead ship a native-image.properties file inside its JAR.
Args = --initialize-at-build-time=com.example.constants \
--initialize-at-run-time=com.example.constants.ClockPlace the file under META-INF/native-image/<groupId>/<artifactId>/. The builder reads every such file on the class path and adds the options to the build. The <groupId>/<artifactId> path prevents two libraries from overwriting each other's files. The second line above shows the usual pattern. It puts a package at build time and carves out one class that must stay dynamic.
Reachability metadata for reflection lives in the same directory, as in the earlier chapters, so one directory per library carries all of its native-image settings.
Choosing between build time and run time
Use these rules to decide.
- Start with the default. Do not add
--initialize-at-build-timeunless you have a reason. - Choose build time for classes that only compute constants, such as lookup tables, parsed immutable configuration, or large precomputed maps. The gain is faster startup.
- Choose run time for any class that reads the environment, the clock or randomness, or that opens files, sockets or threads.
- Prefer a narrow target. Name the specific class or package, not a broad prefix such as
com. - Test the executable, not only the build. A wrong build-time choice usually builds successfully and shows up as wrong values at run time.
Common errors
- "Classes that should be initialized at run time got initialized during image building." Some build-time class reached a class you marked for run time. Use
--trace-class-initializationon the named class and move the triggering class to run time too. - "An object of type ... was found in the image heap" with a Random or thread. A build-time initializer created an object that cannot be saved. Move the owning class to run time.
- Correct build, wrong value at run time. A build-time initializer read the build environment. Move the class to run time, or compute the value lazily inside a method.
- Unexpectedly slow first call. A run-time class does its setup on first use. This is the normal cost. If it matters, consider whether the class is really safe to initialize at build time.
Exercise
A class Config has the field static final String HOME = System.getenv("APP_HOME");. You build with --initialize-at-build-time=Config and set APP_HOME=/srv/app only on the production machine. What does Config.HOME contain there, and how do you fix it?
Show answer
It contains the value of APP_HOME on the build machine, or null if the variable was not set there, because the initializer ran in the builder and the result was saved in the image heap. To fix it, remove the build-time option or use --initialize-at-run-time=Config, so the initializer runs when the executable starts and reads the production environment. Alternatively, read the variable lazily inside a method instead of a static field.
Exercise
Your image build fails because a class initialized at build time indirectly initialized a class you want at run time. Which option helps you find the first link in the chain, and what do you do with the result?
Show answer
Run the build with --trace-class-initialization=<the class>. It prints the call chain that caused the initialization. Then mark the class that triggers the chain, and any of its dependents that need to stay dynamic, with --initialize-at-run-time, so that both sides of the dependency agree.