Scrivio Interview library
LeadershipPrincipal8 min read · updated 12 November 2026

Java's lazy class loading and initialisation suited dynamic frameworks but is a large part of startup cost. GraalVM native image can initialise some classes at build time, and the JDK's AOT cache stores loaded and linked classes. What risks does moving initialisation work earlier carry, and what coding policy should an organisation set so it can use these techniques safely over the years?

Moving initialisation earlier means static state is computed on a build machine or in a training run instead of in production. With native image build-time initialisation, anything a static initialiser captures, such as a timestamp, a random seed, an environment value, a host name or a secret, is frozen into the image, and initialisers that run at a different time or in a different order can change behaviour. The JDK's AOT cache is lower risk because application classes are still initialised normally at run time, and the policy that makes all of these safe is the same: keep static initialisers small, deterministic and free of I/O and environment reads, and do configuration in explicit start-up code.

Why this question is asked

Start-up time used to matter only for desktop applications. Today it decides how quickly a service scales out under load, how much a serverless function costs, and how long a rolling deployment takes. The two main tools for faster Java start-up both move work earlier, and both change assumptions that Java code has relied on for decades. Interviewers ask this at principal level to see whether we can turn a runtime detail into a durable engineering policy. In this answer, we will recap lazy initialisation and why it costs start-up time, look at what native image and the AOT cache each move earlier, go through the concrete risks with examples, and then set out a coding policy and how to enforce it.

1A Quick Recap: Lazy Loading and Its Cost

The JVM loads, links and initialises each class the first time it is used. Initialisation runs the class's static initialiser, its static blocks and static field initialisers. This laziness suited dynamic frameworks well: Spring can scan thousands of classes, generate proxies and wire beans, and only what is used gets loaded.

The cost is paid at every start: a typical Spring Boot service loads 10,000 to 20,000 classes, parsing, verifying and linking each one, and runs a large amount of static initialisation and reflection before it can answer its first request. A start-up of several seconds is common, much of it spent on work that gives the same result every time.

2What Each Technique Moves Earlier

GraalVM native image compiles the application ahead of time into a native executable. As part of the build it can run the static initialisers of selected classes and store the resulting objects in the image heap, a snapshot that is mapped into memory when the executable starts. A class initialised at build time never runs its static initialiser in production; its fields simply already have the values computed on the build machine. Which classes are initialised at build time by default, and how strictly the tool checks this, has changed across GraalVM versions; check your version.

The JDK's AOT cache, introduced through JEP 483 in JDK 24 and made easier to create in JDK 25, records which classes an application loads during a training run and stores them already parsed, verified and linked. In production the JVM maps the cache and skips that work. For application classes, initialisation still happens at the normal time in production, so static initialisers run as before. The JDK may pre-initialise a small number of its own internal classes where it knows this is safe.

Where initialisation runs
TechniqueLoading and linkingStatic initialisers of app classes
Normal JVMat run time, on first useat run time, on first use
JDK AOT cachedone in training, cachedat run time, on first use
Native image, run-time initat build timeat run time, on first use
Native image, build-time initat build timeon the build machine, frozen
Only build-time initialisation changes when our static code runs.

3The Risks of Running Static Code at Build Time

The first risk is captured state. A static initialiser that reads the clock, a random seed, an environment variable, the host name or a file captures the build machine's value, and every instance in production starts with that same value.

Java
public final class RequestIds {
private static final long STARTED = System.currentTimeMillis(); // build time, not start time
private static final Random RANDOM = new Random(); // same seed in every pod
private static final String HOST = hostName(); // the build server's name
private static final String API_KEY = System.getenv("API_KEY"); // a secret baked into the binary
}

Each line is a real production bug when frozen. Uptime metrics report the build time. Every pod generates the same sequence of supposedly random IDs, which can collide and is a security weakness if the values protect anything. Logs and metrics claim every pod runs on the build server. And worst, a secret read at build time is stored inside the executable, where anyone with the image can extract it. Native image tooling detects some of these cases, such as certain objects that must not be in the image heap, but it cannot know that a String is a secret.

The second risk is changed order and timing of side effects. In a normal JVM, a static initialiser that registers a JDBC driver, starts a thread, opens a file or registers a shutdown hook does so when the class is first used, in an order determined by our code. Run at build time, those side effects either happen on the build machine and vanish, or are refused by the build. Code that silently relied on the side effect, such as a static registry that another class fills during its initialisation, may find it empty or differently ordered in the image.

4Why the AOT Cache Is Lower Risk

The AOT cache keeps normal initialisation semantics for application code: static initialisers still run in production, at the same point, in the same order, reading the production environment. What is reused is the work of parsing, verifying and linking, which gives the same result regardless of the environment. The main operational caveats are that the cache must be created with the same JDK build and a compatible class path, and that a cache from a training run that did not exercise a code path does not help that path; in both cases the JVM falls back to normal loading rather than behaving differently. So for most teams, the AOT cache is a start-up gain with very little behavioural risk, while native image build-time initialisation needs code that is written for it.

5The Policy: Small, Deterministic Static Initialisers

The policy that makes code safe for all of these techniques, today and as their defaults change, is short. Static initialisers may only compute values that are the same on every machine and at every moment: constants, lookup tables, precompiled Patterns, immutable maps built from literals. They must not perform I/O, read the environment, system properties, the clock, random sources or the network, start threads, register global hooks, or hold secrets. Anything that depends on where or when the program runs belongs in explicit start-up code, such as a Spring bean, a configuration properties class, or a main method that builds the objects and passes them on.

Java
// Allowed: deterministic, no I/O
private static final Pattern SKU = Pattern.compile("[A-Z]{3}-\\d{4}");
private static final Map<String, Integer> PRIORITY = Map.of("high", 1, "low", 3);
// Moved to start-up code: depends on the environment
@ConfigurationProperties("payments")
public record PaymentsProperties(String apiKey, Duration timeout) { }
@Bean
RandomGenerator ids() { return RandomGenerator.of("L64X128MixRandom"); } // created per process at start

Code that follows the policy behaves identically under lazy loading, with an AOT cache, and in a native image with build-time initialisation, because there is nothing time- or place-dependent to capture. The same rule also prevents unrelated problems: static initialisers that cannot fail cannot poison a class with NoClassDefFoundError, and initialisers that do not touch other classes' state cannot deadlock with each other.

6Enforcing It Over the Years

A policy that lives only in a wiki decays. To keep it, we encode it in tools. A static analysis rule, written for example with ArchUnit or an Error Prone check, can flag static field initialisers and static blocks that call System.getenv, System.getProperty, currentTimeMillis, new Random, file and network APIs, or Thread.start. Code review guidelines cover the cases tools miss. For services that build native images, the build runs with the tool's strict reporting of build-time initialisation and fails on new classes initialised at build time unless they are on an approved list. And a start-up test compares a few values, such as the start timestamp and a random sample, across two launches of the same artifact to catch frozen state.

7Follow-up questions

Is it safe to initialise third-party library classes at build time?

Only after checking what their static initialisers do, and only for the versions checked. Many libraries are designed for it and ship native image configuration that marks safe classes. Others read system properties or the environment in static blocks, such as logging frameworks choosing their configuration, and initialising those at build time freezes the build machine's settings. The safe default is run-time initialisation for library classes unless the library documents otherwise.

Does Spring's own AOT processing initialise beans at build time?

No. Spring's AOT engine generates source code at build time that replaces reflection and bean definition parsing, but the beans themselves are still created at run time with the production configuration. It works well with both native image and the JDK AOT cache, and it is another reason to keep environment-dependent work in beans rather than in static initialisers.

8Conclusion

In this answer, we saw that native image build-time initialisation and the JDK AOT cache both move work earlier, but in different ways. Build-time initialisation runs static initialisers on the build machine and freezes their results, which can capture timestamps, random seeds, environment values, host names and secrets, and can change the timing and order of side effects, with defaults that differ across versions. The AOT cache only reuses loading and linking and keeps normal initialisation, so it is lower risk. The durable policy is small, deterministic static initialisers with no I/O or environment reads, configuration in explicit start-up code, and tools that enforce it.

What to say in the interviewAbout 100 seconds aloud

Open with

Both techniques move work earlier, but they move different work. The JDK AOT cache, from JDK 24 on, records classes during a training run and stores them already parsed, verified and linked, but application classes are still initialised in production at the normal time, so static initialisers see the production environment.

Then, if they want more

That is low risk. Native image can go further and run static initialisers on the build machine, storing the results in the image heap. Then whatever those initialisers captured is frozen: a start timestamp, a Random seed that becomes identical in every pod, the build server's host name, environment values, even secrets baked into the binary.

Side effects such as registering drivers, starting threads or filling static registries happen on the build machine or in a different order, which can change behaviour. And which classes are initialised at build time by default has changed across GraalVM versions, so it is not stable ground.

So the policy I would set is simple: static initialisers may only compute deterministic values, constants, lookup tables, precompiled patterns, and must not do I/O, read the environment, properties, the clock or randomness, start threads or hold secrets. Configuration goes into explicit start-up code like Spring configuration properties and beans.

I would enforce it with static analysis rules, strict build-time initialisation reporting in native builds, and a start-up test across two launches. Code written that way works the same with lazy loading, AOT caches and native image.

About this answer

Last updated
12 November 2026
Versions it names
Java 24, Java 25
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Java's lazy class loading and initialisation suited dynamic frameworks but is a large...": https://scrivio-interview-library.netlify.app/java/class-loading/90f0a5de6e/