Sub topic 1
From source file to running program: the JVM pipeline
Prerequisites
This chapter assumes you can do the following:
- Write, compile and run a basic Java program with
javacandjava. - Read classes, methods, static members and exceptions without explanation.
- Use a terminal and pass options to a command-line tool.
It is the overview chapter. Each stage below gets its own chapter later in the tutorial, so here you build a map and run a few experiments.
Why the pipeline matters
When you type java Hello, three separate things happen. javac has already turned source text into a file of bytecode. The JVM then locates, loads and checks that file at run time. Finally, the JVM executes the bytecode, first by interpreting it and later by compiling hot parts to machine code.
Many confusing Java problems come from mixing up these stages. A NoClassDefFoundError is a run-time loading problem, not a compile-time one. A static initializer that "runs too late" is a consequence of lazy initialization. A program that is slow for its first second and fast afterwards is warming up its JIT compiler. Knowing which stage a symptom belongs to tells you where to look.
The stages at a glance
The first arrow happens at build time, on a developer machine or a build server. Everything after it happens inside a running JVM process, and most of it is lazy: the JVM does the work for a class only when the program first needs that class.
| Stage | Happens when | Input | Output |
|---|---|---|---|
| Compilation | Build time | `.java` source | `.class` files |
| Loading | First use of a class | Bytes of a class file | A class in memory |
| Linking | After loading | A loaded class | A verified, prepared class |
| Initialization | First active use | A linked class | Static state set up |
| Execution | Method calls | Bytecode | Running behavior |
Stage 1: compilation to bytecode
javac parses your source, checks types, and writes one .class file for every class it finds, including nested and anonymous classes. A nested class Outer.Inner becomes Outer$Inner.class.
The class file is not machine code. It holds bytecode, a compact instruction set for an abstract stack machine. Because every JVM understands the same instruction set, the same .class file runs on Linux, Windows or macOS. This is the origin of "write once, run anywhere". The next chapters open up the file format and the instructions.
Create a small program and compile it:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, JVM");
}
}javac Hello.java
ls
javap -v Hello | head -n 12The javap -v output includes the lines minor version: 0 and major version: 55. Major version 55 means the file was produced for Java 11. A JVM refuses to load a class file whose major version is newer than it supports, which is why code compiled with a newer JDK fails on an older runtime with UnsupportedClassVersionError.
JDK 11 also adds a shortcut: java Hello.java compiles the single file in memory and runs it without writing a .class file. That is convenient for experiments, but the stages are the same. The compiler still runs first.
Stage 2: starting the JVM and finding the main class
The java launcher is a small native program. It does the following:
- Parses the options and picks the main class (or the main class of a JAR).
- Creates the JVM inside the process, which sets up the heap, the thread stacks, the bootstrap class loader and the execution engine.
- Asks the JVM to load the main class, link it and initialize it.
- Looks up
public static void main(String[])in that class and calls it on the main thread.
Step 3 comes before step 4. The static initializers of your main class run before main starts. If one of them throws, you see ExceptionInInitializerError and main never runs.
Stage 3: loading, linking, initialization
The JVM does not load the whole program at startup. It loads a class when running code first needs it, for example when it executes new, calls a static method or reads a static field. This lazy approach keeps startup fast, and it explains why a missing class can stay hidden until the line that uses it executes.
For each class, the JVM goes through three phases:
- Loading finds the bytes of the class file and creates an in-memory representation of the class. Class loaders do this work, and Chapters on the loader hierarchy and delegation cover them.
- Linking has three parts. Verification checks that the bytecode is structurally safe. Preparation allocates static fields and gives them default values such as
0ornull. Resolution turns symbolic references in the class file into direct references to other classes, methods and fields. - Initialization runs the class's static initializer, which means static field initializers and
static { }blocks, in the order they appear in the source.
You can watch this laziness directly:
public class Pipeline {
static class Late {
static {
System.out.println("Late initialized");
}
static void hi() {
System.out.println("hi");
}
}
public static void main(String[] args) {
System.out.println("main started");
Late.hi();
}
}javac Pipeline.java
java PipelineThe output is:
main started
Late initialized
hiLate is not initialized until Late.hi() is called. Its static block runs just before the method body.
The JVM can log the loading half of this. In Java 9 and later, unified logging does it:
java -Xlog:class+load:file=classload.log PipelineOpen classload.log. It lists hundreds of classes from the JDK itself, such as java.lang.Object and java.lang.String, before it reaches Pipeline and Pipeline$Late. Each line ends with a source: field. For JDK classes it names a shared archive or the jrt:/ runtime image, and for yours it names a file path. The JDK classes appear first because the JVM needs them to start at all.
A note on terms: "loaded" and "initialized" are different states. A class can be loaded and linked without being initialized. For example, the JVM may load a class to check a type, and initialization waits until the first active use. Later chapters list exactly which actions count as active use.
Stage 4: execution
Once main is called, the execution engine runs bytecode. HotSpot, the JVM in the standard OpenJDK builds, uses two techniques together:
- The interpreter reads bytecode instructions one at a time and performs each. It starts instantly but is slow.
- The JIT compiler (just-in-time compiler) translates frequently used methods into native machine code while the program runs. HotSpot counts method invocations and loop iterations to find these "hot" methods.
This mix explains warm-up behavior. The first calls to a method are interpreted. After enough calls, the method is compiled and later calls get faster. Micro-benchmarks that skip warm-up measure the interpreter and give misleading results.
While executing, the JVM uses several memory areas:
| Area | Holds | Shared between threads |
|---|---|---|
| Heap | Objects and arrays | Yes |
| Metaspace | Class metadata, method bytecode, the run-time constant pool | Yes |
| Thread stack | One frame per active method call | No, one per thread |
The heap is managed by the garbage collector. Metaspace lives in native memory, outside the heap, and grows as classes load. Each thread has its own stack, and every method call pushes a frame holding that call's local variables and operand stack. Chapters 4 and 6 cover these areas in detail.
Common mistakes at this level
- Treating compile errors and loading errors as the same.
javacreports type errors before the program exists.ClassNotFoundExceptionandNoClassDefFoundErrorappear only at run time, usually because the class path differs from the one used for compiling. - Assuming all classes load at startup. A class that is never reached is never loaded, so a broken dependency can pass tests that never touch it.
- Assuming static initializers run when the program starts. They run on first active use of the class, apart from the main class, which is initialized before
main. - Benchmarking without warm-up. Cold code runs in the interpreter, so first-run timings say little about steady-state speed.
- Mixing JDK versions. Compiling with a newer JDK and running on an older one fails on the class file version, even if the source uses no new APIs. The
--releaseoption ofjavacprevents this.
Where the rest of the tutorial goes
The following chapters take each stage apart. First the class file and its constant pool, then the memory areas and bytecode with javap. Then frames and method invocation, and after those the class loaders, parent delegation, linking, initialization, custom loaders and the errors they cause. The last chapter returns to the interpreter and JIT compiler.
Exercise
You run java Pipeline for the program in this chapter, but you delete Pipeline$Late.class first and change main so that it never calls Late.hi(). Does the program still print "main started" without error? What happens if main does call Late.hi()?
Show answer
If main never touches Late, the JVM never loads it, so the missing file is not noticed and the program prints "main started" normally. If main calls Late.hi(), the JVM tries to load Pipeline$Late at that point and fails with NoClassDefFoundError, after "main started" has already been printed. Loading is lazy and happens on first use, so the error appears at run time, at the line that needs the class.
Exercise
Put these events in the order they happen for java Hello: main is called, javac writes Hello.class, the static initializer of Hello runs, Hello is verified, the bytes of Hello.class are read.
Show answer
1. javac writes Hello.class (build time). 2. The bytes of Hello.class are read (loading). 3. Hello is verified (linking). 4. The static initializer of Hello runs (initialization). 5. main is called.