Sub topic 1
From bytecode on a JVM to a standalone executable
This chapter explains what a JVM does between your .class files and running machine code, and how GraalVM Native Image moves most of that work to build time. It is the first of 13 chapters, so it sets up the model that later chapters build on: static analysis, metadata, initialization and the trade-offs of the native approach.
Prerequisites
This chapter assumes you can do the following:
- Write, compile and run a basic Java program from the command line with
javacandjava. - Explain what a JAR file and the classpath are.
- Describe, in general terms, what the JVM and JIT (just-in-time) compilation do.
You do not need Maven or Gradle experience yet. Build tool integration comes in a later chapter.
What the JVM does with your program
When you run java -jar app.jar, the JVM does a lot of work before and during your main method. The following steps happen at run time, on every launch.
- Start the runtime. The JVM initializes its heap, threads, garbage collector and class-loading machinery.
- Load classes. Class loaders find
.classfiles in the JAR or the JDK modules, read them, and parse them into internal structures. - Verify and link. The bytecode verifier checks each class for type safety. Linking then prepares static fields and resolves symbolic references.
- Initialize classes. Static initializers (
static { ... }blocks and static field initializers) run the first time a class is actively used. - Interpret, then compile. Bytecode first runs in an interpreter. The JVM counts how often each method runs and how often loops iterate. Hot code goes to the JIT compilers, which produce optimized machine code.
The JIT compiler is the reason Java reaches high throughput. It observes the running program, so it can make optimistic decisions. For example, it can inline a virtual call because only one implementation has been seen so far. If that assumption later fails, the JVM deoptimizes: it discards the machine code and falls back to the interpreter.
The price is that every launch repeats the loading, verification, warm-up and compilation. A short-lived command-line tool, or a function that a cloud platform starts on demand, pays that cost every time. A JVM process also keeps metadata, profiling data and compiled code in memory, so its footprint is larger than the application's own data would suggest.
Ahead-of-time compilation
Ahead-of-time (AOT) compilation translates your program to machine code before it runs, as a separate build step. GraalVM Native Image is an AOT compiler for Java. It takes your application classes, the libraries they use, and the parts of the JDK they need, and produces one native executable for a specific operating system and CPU architecture.
The following table shows where each task happens.
| Task | JVM (`java`) | Native Image |
|---|---|---|
| Load and parse classes | At run time | At build time |
| Verify bytecode | At run time | At build time |
| Run most static initializers | At run time | At run time by default, with some at build time (see the initialization chapter) |
| Compile to machine code | At run time (JIT) | At build time (AOT) |
| Memory management | HotSpot JVM and its collectors | A runtime called Substrate VM, embedded in the executable |
The executable does not need a JVM installed. It still has a runtime, though. Native Image embeds Substrate VM, a small runtime that supplies garbage collection, thread support and other services. A native executable is therefore not "Java without a runtime". It is Java with a much smaller runtime, linked into the binary.
Build time and run time are different worlds
Native Image works in two phases, and keeping them apart will save you a lot of confusion later.
- Build time. The
native-imagetool starts a JVM, analyzes your program, and compiles everything it finds reachable. It can also run some code and save the resulting objects in the image heap. - Run time. The finished executable starts. Its code is already compiled and its initial heap is already laid out, so there is no class loading, no bytecode verification and no JIT warm-up.
Building your first native executable
You need a GraalVM distribution that includes the native-image tool, and on Linux and macOS a C toolchain (a compiler and linker) that the tool uses to link the final binary. Check that the tool is available:
native-image --versionStart with a minimal program.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, native image!");
}
}Compile it with javac, build the native executable, and run it.
javac Hello.java
native-image Hello
./hellonative-image Hello takes the main class name as its argument. It writes an executable named after the class, in lowercase (hello). On Windows the file is hello.exe. Running ./hello prints the greeting without starting a JVM.
The build takes noticeably longer than javac. Even for this tiny program it typically takes several seconds and uses a gigabyte or more of memory, because the tool analyzes parts of the JDK as well as your class. This is normal.
Building from a JAR
Most real applications ship as an executable JAR. Pass it with -jar, and name the output with -o:
native-image -jar app.jar -o appWithout -o, the executable takes its name from the JAR file. The JAR must have a Main-Class entry in its manifest. Dependencies must be reachable: either bundled in the JAR, or listed on the classpath with -cp.
What you get and what you give up
The executable is a different kind of artifact from a JAR, and it behaves differently.
- Startup is fast. There is no class loading, verification or warm-up. Many applications start in milliseconds instead of hundreds of milliseconds or seconds.
- Memory use is lower. There is no JIT compiler in the process, no profiling data, and no class metadata for code that was removed.
- It is platform-specific. An executable built on Linux x64 will not run on macOS or Windows. You build once per target platform.
- Builds are slow and heavy. Analysis and compilation of the whole program takes time and memory. You normally do day-to-day development on a regular JVM and build native images in CI or before release.
- Peak throughput can be lower. With no run-time profile, the AOT compiler cannot make the optimistic decisions a JIT can. Chapter 10 returns to this, including profile-guided optimization, which narrows the gap.
- Some Java features need extra help. The compiler decides at build time what to include. Code that finds classes by name at run time is a problem, and the next chapters cover it.
To see the last point, look at a program that loads a class by a name known only at run time.
public class Reflective {
public static void main(String[] args) throws Exception {
Class<?> c = Class.forName("com.example.Greeter");
Object o = c.getDeclaredConstructor().newInstance();
System.out.println(o);
}
}On a JVM this works as long as com.example.Greeter is on the classpath. In a native image, the build tool sees only a string. Unless metadata registers Greeter, the build may leave the class out, or keep it without the constructor, and the call fails at run time. The cause is the closed-world assumption, which the next chapter explains. The fix is reachability metadata, which comes after that.
Choosing between a JVM and a native executable
The decision depends on the workload, so there is no universal answer. Use these questions as a starting point.
| Question | Leans toward JVM | Leans toward native image |
|---|---|---|
| How long does the process live? | Hours or days | Seconds or minutes, or scaled to zero |
| What limits cost? | Peak throughput | Memory per instance, instance count |
| How dynamic is the code? | Heavy reflection, runtime class generation, plugin loading | Mostly static code and libraries with native support |
| How fast must the build be? | Fast feedback needed | Slow builds are acceptable in CI |
| How many target platforms? | Many, with one artifact | A few, with one build each |
A command-line tool, a serverless function, and a microservice that scales out often are good candidates. A long-running service with a large heap and heavy dynamic behavior often runs better on a JVM.
Common misconceptions
- "Native Image makes Java code faster." It makes startup faster and memory smaller. Peak speed after warm-up is often equal or lower than HotSpot's.
- "The executable is portable." It is not. It contains machine code for one platform.
- "Native Image compiles source code." It compiles bytecode, so any JVM language that produces bytecode, such as Kotlin or Scala, can be a source, subject to library support.
- "There is no runtime." There is Substrate VM, and it handles garbage collection and threads.
Exercise
A team runs a Java tool as a short-lived job that starts about 50,000 times a day, and each run lasts two seconds. Most of the time is spent starting the JVM and warming up. Name two reasons a native executable fits this job, and one thing the team must do that they did not need to do on the JVM.
Show answer
Two reasons: (1) the executable skips class loading, bytecode verification and JIT warm-up, so startup is much faster; (2) it uses less memory per process because it has no JIT compiler or profiling data. The team must build a separate executable for each target platform, and they must test the native executable itself, because dynamic features such as reflection can fail at run time even when the build succeeds. They also have to accept slower builds.
Exercise
You run javac Hello.java and then native-image Hello. What is the name of the output file on Linux, and which command would you use to build an executable named app from app.jar?
Show answer
The output file is hello, named after the main class in lowercase. To build from the JAR, use native-image -jar app.jar -o app.