Sub topic 1
JIT on the JVM versus ahead-of-time native executables
This chapter explains the two ways a Spring Boot application can turn Java code into running machine instructions. It covers the JVM with its just-in-time (JIT) compiler and the GraalVM native executable built ahead of time (AOT). Later chapters cover the build steps. Here you build the working model that explains every trade-off that follows.
Prerequisites
This chapter assumes you have the following:
- Java 17 or later and basic Spring Boot knowledge: beans, auto-configuration, and application properties.
- Experience building Spring Boot projects with Maven or Gradle.
- Basic container concepts, such as images and running a container with Docker.
- A conceptual familiarity with Java reflection and dynamic proxies.
You do not need GraalVM installed to read this chapter. The commands shown here are previews of material covered later in the tutorial.
How a Java program normally runs
When you run java -jar app.jar, you start a Java Virtual Machine (JVM). A JVM is a process that loads compiled Java classes and executes them. The compiler javac does not produce machine code. It produces bytecode, a portable instruction set stored in .class files.
The JVM runs bytecode in stages:
- Class loading. The JVM finds classes on the classpath, reads their bytecode, verifies it, and links it. This happens lazily, the first time a class is needed.
- Interpretation. The JVM first runs bytecode with an interpreter. This starts immediately but is slow per instruction.
- Profiling. While interpreting, the JVM counts how often methods are called and which branches are taken.
- JIT compilation. When a method becomes "hot", the JIT compiler translates it to optimized machine code while the program runs. HotSpot uses several tiers, so a method may be compiled more than once, with increasing optimization.
- Deoptimization. If an assumption made by the compiled code stops being true, the JVM discards that machine code and falls back to the interpreter.
The key idea is that the JVM decides how to optimize based on observed behavior at runtime. This is why a long-running JVM can reach very high throughput. It can inline methods through interface calls because it has seen that only one implementation is ever used, and it can remove branches that never execute.
The cost of that model
The same flexibility has a price, and it matters most for Spring Boot applications.
- Startup time. Before the first request, the JVM loads thousands of classes, and Spring scans the classpath, reads annotations, evaluates auto-configuration conditions, creates bean definitions, and builds proxies. All of this happens in interpreted or lightly compiled code.
- Warm-up. Peak speed arrives only after the hot methods have been profiled and compiled. The first requests are slower than later ones.
- Memory. The process holds the JIT compiler, the profiling data, loaded class metadata, and compiled code in addition to your objects. A small service often needs several hundred megabytes of resident memory.
- Package size. You ship an application plus a JVM, or an image that contains one.
For a service that runs for days on a large host, these costs are small relative to the benefit. For a short-lived function, a scale-to-zero container, or a command-line tool, they can dominate.
What ahead-of-time compilation changes
With ahead-of-time compilation, the translation to machine code happens once, during the build, not in each running process. GraalVM Native Image is a tool that does this for Java. It takes your application, its dependencies, and the parts of the JDK that it needs, analyzes them, and produces a single platform-specific executable.
You build and run it like this:
./mvnw -Pnative native:compile
./target/demoThe file target/demo is a native executable. It starts without a JVM installed. It contains:
- Machine code for your code, your libraries, and the used parts of the JDK.
- A runtime called Substrate VM, which provides memory management (garbage collection), thread support, and other services that the JVM normally gives you.
- A snapshot of the image heap: objects that were created and initialized during the build, stored directly in the executable.
The image heap is an important source of the startup gain. Work done at build time does not need to be repeated at every start.
Side-by-side comparison
| Aspect | JVM with JIT | Native executable |
|---|---|---|
| Compilation happens | At runtime, while the program runs | At build time, once |
| Input to optimization | Observed runtime behavior | Static analysis of the code |
| Startup time | Typically seconds for a Spring Boot app | Typically tens of milliseconds |
| Peak throughput | Often higher after warm-up | Often equal or lower, unless profile-guided optimization is used |
| Memory footprint | Larger | Smaller |
| Build time and resources | Seconds, light | Minutes, memory-hungry |
| Dynamic features | Fully supported | Restricted, need configuration |
| Portability | One JAR runs on any JVM platform | One executable per operating system and CPU architecture |
| Tooling | Debuggers, JFR, agents, hot swap | Different, more limited tooling |
The startup and memory figures depend on the application, so treat the words "typically" as orders of magnitude and measure your own service.
Where the time goes at startup
The diagram shows what each model does between launching the process and serving the first request.
In the native model, most of the boxes on the left have moved into the build step. The price is that the build must know everything the application will need.
Throughput is not always better on the JVM
It is tempting to summarize the comparison as "native starts faster, JVM runs faster". This is a useful default but not a rule.
- A JIT compiler can use runtime profiles that a static compiler lacks. That is why the JVM often wins on long, compute-heavy workloads.
- Native Image can use profile-guided optimization (PGO). You run an instrumented build under a representative workload, save the profile, and feed it into the final build. This narrows the throughput gap, but it adds build steps and depends on a representative workload. Availability of some features depends on the GraalVM distribution you use.
- Garbage collection differs. The default collector in a native executable is simpler than the best JVM collectors, so latency and throughput under heavy allocation can differ. Check which collectors your GraalVM version supports.
- Many web services are not limited by raw compute. They wait on databases and networks, so the compiler matters less than startup time and memory.
What native executables give up
Because the compiler decides everything before the program runs, some Java features no longer work as they do on the JVM:
- Dynamic class loading. You cannot load arbitrary classes from the classpath or from a network location at runtime.
- Reflection, resource lookup, and dynamic proxies work only for elements that were declared to the build.
- Runtime bytecode generation, used by some libraries, is not available in the same form.
- JVM tooling. Java agents, standard JVM attach mechanisms, and some monitoring approaches do not apply.
This is the reason Spring Boot 3 includes ahead-of-time processing. Spring does at build time much of the work that it used to do through reflection and classpath scanning at startup. Both topics appear in later chapters. For now, keep the principle in mind: native images trade runtime flexibility for work done earlier.
A worked comparison
Suppose you have a small REST service called demo. You can measure both modes the same way, using Spring Boot's startup log line.
# JVM mode
./mvnw package
java -jar target/demo.jar
# Native mode (needs GraalVM installed)
./mvnw -Pnative native:compile
./target/demoSpring Boot prints a line like Started DemoApplication in N seconds. In JVM mode, a small service often reports on the order of one to three seconds. In native mode, the same service often reports well under a tenth of a second. To compare memory on Linux, check the resident set size of the running process:
ps -o rss,cmd -p "$(pgrep -f demo)"Run each mode several times and ignore the first run. Also send some requests before you compare. A startup measurement alone does not show the warm-up effect, and a few requests will show you the JVM's early slowness and, later, its improvement.
Common misunderstandings
- "Native Image makes Java code faster." It mainly makes startup faster and memory smaller. Peak throughput can be lower.
- "A native executable is portable." It is compiled for one operating system and CPU architecture. Build on each target, or use a container build that matches it.
- "If it works on the JVM, it works as a native image." Not necessarily. Code that relies on reflection or dynamic proxies without declared metadata can fail only in native mode. Chapters later in this tutorial show how to find and fix these failures.
- "Native builds are as quick as normal builds." They commonly take minutes and need much memory, so plan for CI resources and for developing and testing mostly on the JVM.
Summary of the working model
Keep this model for the rest of the tutorial:
- On the JVM, bytecode is interpreted and then compiled by the JIT while the program runs. This gives flexibility and strong peak performance, at the cost of startup time and memory.
- In a native executable, compilation happens once at build time. The result starts fast and uses less memory, but it can only contain what the build could see.
- The next chapter explains why: the closed-world assumption.
Exercise
A team runs a Spring Boot service as a long-lived process that handles heavy computation for days at a time on a large server. Another team runs a Spring Boot function that is started on demand and often lives for a few seconds. Which compilation model fits each team better by default, and which property of each model justifies your answer?
Show answer
The first team's service usually fits the JVM with JIT better. It runs long enough to pay off the warm-up cost, and the JIT can use runtime profiles to reach high peak throughput, so startup time and memory matter less. The second team's function usually fits a native executable better. It lives briefly, so fast startup and a small memory footprint dominate, and JIT warm-up would never finish. Both answers are defaults. Measure the real workload, and consider that native builds restrict reflection and dynamic features.
Exercise
Name three things that a native executable contains that a plain JAR does not, and one thing it cannot do that a JVM can.
Show answer
A native executable contains machine code compiled at build time, the Substrate VM runtime (memory management and thread support), and a snapshot of the image heap with objects initialized during the build. A JAR contains bytecode and needs a JVM to run. A native executable cannot load arbitrary classes dynamically at runtime. It also needs declared metadata for reflection, resources, and proxies.