Lesson · JVM Internals
JVM architecture: three subsystems and a stack machine
15 min readJVM Architecture
The class loader subsystem, the runtime data areas and the execution engine, plus the design decision that shapes every instruction: the JVM computes on an operand stack, not on named registers. One map, three subsystems, and the error messages each of them owns.
One artifact, many machines
A build server compiles one .class file, and it runs unchanged on a laptop, in a container and on a mainframe. Something has to make that portability real: a runtime that accepts the same binary everywhere and absorbs the platform differences itself. That runtime is the JVM, and this lesson is the map of its three subsystems.
The journey of a .java file already walked the whole pipeline at a glance. Here we open the box labelled JVM and look inside: who brings classes in, where the state lives while the program runs, and what actually executes the instructions.
The JVM is one name in a stack of three, and this part opens the layer the others contain. The roadmap part's installing-java lesson defines the acronyms properly; keep this recap at hand, because the tooling lesson later in this part is entirely about the outermost layer.
| Layer | What it adds | Where you meet it |
|---|---|---|
| JVM | the machine that executes bytecode: loader, runtime areas, execution engine | this part, starting with the diagram below |
| JRE | the JVM plus the core class libraries in java.base and friends | what a deployment needs to run a program, nothing more |
| JDK | the JRE plus the development tools: javac, jar, jshell, javap, jcmd, jlink | what you installed, and what sits in its bin directory |
- Class loader subsystem: loads the classes.
- Runtime data areas: hold the data while the program executes.
- Execution engine: executes the instructions.
The JVM is a program whose input is a class file and whose job is to adapt it to one specific machine. Every part in this lesson exists to serve that adaptation.
Three subsystems, three jobs
Every JVM, from a phone to a data centre, is built from the same three parts. The names matter less than the responsibilities, because every runtime error you will ever debug belongs to exactly one of them.
| Subsystem | Owns | Typical failure |
|---|---|---|
| Class loader | Finding class files, linking them, running their static initialization | ClassNotFoundException, NoClassDefFoundError, an initialization that does not happen at the start |
| Runtime data areas | All state: per-thread frames, plus heap and class metadata shared by everyone | OutOfMemoryError (heap, metaspace, direct buffers), StackOverflowError |
| Execution engine | Interpreting bytecode, JIT-compiling hot methods, releasing memory no object can use again | Slow warm-up, exhausted code cache, garbage collection pauses |
Load it, store it, run it. When an error lands in your lap, name the subsystem first; the fix lives in exactly that one.
Subsystem 1: the class loader
The loader subsystem answers one question per class: where does this class come from? A name like java.util.List is resolved against an ordered set of places (the module path, the classpath, later a custom source such as a jar, a directory or a network), and the result is a Class object plus the metadata the rest of the runtime needs.
Loading is not a single step, and the three phases do not happen at the same moment: bytes may be read long before the class is initialized. The class loading lesson owns the mechanics and the triggers; here is the shape of the work.
- Load: read the bytes, check the magic number and the version, produce the Class object. A missing file ends here as ClassNotFoundException.
- Link: verify the bytecode (types, stack shapes, jump targets), prepare static fields with default values, resolve symbolic references from the constant pool as they are used.
- Initialize: run static field initializers and static blocks, in source order, once per class per loader. This is the phase whose triggers get their own lesson.
- Delegation: loaders form a parent chain, and JDK classes are resolved through the platform loaders first, so java.lang.String can never be shadowed by a lookalike class.
- User-defined loaders: subclassing ClassLoader lets a framework load code from anywhere: plugins, application servers, build tools, bytecode generators.
Loading is lazy, and that is a feature. The JVM brings a class in at its first active use, not at startup, which keeps boot fast and makes load order a debugger-visible property rather than a mystery.
Subsystem 2: the runtime data areas
State has to live somewhere, and the runtime data areas divide it with one question: who can see it? Each thread owns its execution state; classes and objects are shared by everyone. The diagram below is that map.
Read the table that follows as the same picture in words: the Owner column is what matters, because ownership decides both the failure mode and the flag that controls the size.
| Area | Owner | Holds | Size flag |
|---|---|---|---|
| PC register | One per thread | The address of the instruction being executed; undefined while native code runs | n/a |
| JVM stack | One per thread | One frame per active call: locals, operand stack, constant pool reference | -Xss |
| Native method stack | One per thread | Frames of native (non-Java) methods | -Xss |
| Heap | Shared | Every object and array; this is the area the garbage collector manages | -Xmx |
| Method area | Shared | Per-class metadata: the constant pool, field and method descriptions, the bytecode itself | -XX:MaxMetaspaceSize |
| Code cache | Shared | Native code the JIT produced for hot methods (an implementation extra) | -XX:ReservedCodeCacheSize |
| Direct memory | Shared | Off-heap buffers from ByteBuffer.allocateDirect (an implementation extra) | -XX:MaxDirectMemorySize |
- Method area vs Metaspace: the JVMS defines the method area as an abstraction; HotSpot implements it as Metaspace in native memory since Java 8. The older PermGen was the same metadata held inside the heap, sized by hand with -XX:MaxPermSize, which is why class loader leaks used to look like heap leaks.
- Frames are created and destroyed constantly: one per invocation, popped on return, whether that return is a normal one or an exception unwinding the stack.
- The heap is one logical area per JVM, even when the collector splits it into generations or regions. Those divisions are the collector's business, not the specification's.
The spec names areas; the implementation chooses the plumbing. The JVMS requires the heap and the method area to behave a certain way, not to be laid out in any particular place or shape.
JVM · one instance
load it, store it, run itWhere this picture sits
each layer contains the one inside itJDK
what you install: libraries + tools (javac, jcmd, jshell)JRE
what runs a program: the core class librariesJVM
the machine mapped belowclass loader subsystem
brings classes inLoaders form a parent chain, and user-defined loaders plug in here: plugins, app servers and build tools all supply their own.
runtime data areas
where all state livesper thread · one set each
shared · one per JVM
The spec names the stacks, the heap and the method area. The starred rows are HotSpot extras, not JVMS areas.
execution engine
turns bytecode into behaviourThe engine reads bytecode from the method area and works on the frames each thread already owns; it adds no state of its own.
The spec names the areas; the implementation chooses the plumbing. Both statements have to be true at once for the map to make sense.
The JVM computes on a stack
Look at any CPU and you find registers: named storage that instructions read and write. Bytecode has none. Its instructions take their inputs from an operand stack and leave their results there, and the only state they can touch outside that stack is the array of local variables.
The method below is small enough to hold in your head. Step through it and watch the stack rise and fall: values go up, the operator pops them, and the result comes back down into a local. Then a second thread calls the same method, and the difference between shared code and private frames becomes visible.
static int expr(int i, int j) { int k = i + j * 2; // iload_0, iload_1, iconst_2, imul, iadd, istore_2 return k; // iload_2, ireturn }
The JVM is a stack machine: every operation pushes and pops. That is how bytecode stays compact and portable, and it is why every frame carries an operand stack next to its locals.
Operand stack · method expr
bytecode · one copy, shared by every thread
locals
operand stack
empty
A call to expr(7, 5) pushes one frame: locals for the parameters, an empty operand stack, and a reference to the constant pool of the class. Local 2 belongs to k and has no value yet, because the verifier will not let anything read it before istore_2 writes it.
Subsystem 3: the execution engine
The engine is where bytecode becomes behaviour. In HotSpot it is three cooperating pieces rather than one loop, and each piece is the answer to a different cost problem.
- Interpreter: executes bytecode directly. It starts instantly and stays the fallback for code that runs once, or runs before profiling has evidence.
- JIT compilers: the JVM profiles the running program and compiles hot methods. C1 compiles quickly with light optimization; C2 waits for more evidence and optimizes hard. Tiered compilation runs both, in stages.
- Garbage collector: the memory manager of the heap. It finds objects that can never be reached again and makes their memory available; the spec requires automatic reclamation, not any particular algorithm.
- The engine reads, it does not own: it executes bytecode that lives in the method area, and it works on frames that live on each thread's JVM stack. The subsystems cooperate rather than duplicate state.
Interpretation starts the program; compilation makes it fast. The engine is built around that handoff, and the Execution Engine & JIT lesson takes the machinery apart.
One spec, many implementations
The JVM specification describes behaviour: what a class file must contain, what each instruction must do, which errors must be thrown. It deliberately does not describe layout. Nothing in it says where an object header lives, how the heap is divided, or whether locals sit in memory when nobody can observe the difference.
That freedom is why one .class file runs on several implementations, and why performance work is implementation work. HotSpot is the default, but it is one implementation among others, and parts of the table above are its choices rather than the specification's requirements.
- Objects: the spec says instances have fields; HotSpot adds a two-word header, aligns the layout, and compresses references so most heaps use 32-bit pointers.
- Frames: the spec says a frame has locals and an operand stack; after escape analysis a JIT may keep both in registers, as long as no observer can tell.
- Threads: the spec says a JVM supports many threads of execution; it does not require an operating-system thread per Java thread. HotSpot maps platform threads one to one, and schedules virtual threads itself.
- Garbage collection: the spec requires reclamation of the heap; serial, parallel, G1, ZGC and Shenandoah are all legal answers to the same requirement.
Ask whether a fact is spec or implementation before quoting it. Half of the surprises in JVM interviews come from stating one as the other.
Where the map meets your logs
This is the payoff of the whole lesson: each familiar message names its subsystem, and the fix follows from the area it describes rather than from a guess.
| Message | Subsystem | What it tells you |
|---|---|---|
| StackOverflowError | JVM stack (per thread) | A call chain filled one thread's stack: fix the recursion depth or raise -Xss, and leave -Xmx alone |
| OutOfMemoryError: Java heap space | Heap (shared) | Live objects, or references that keep them alive, hold more memory than the heap can supply |
| OutOfMemoryError: Metaspace | Method area (shared) | Classes keep being defined and never released: usually a class loader leak |
| OutOfMemoryError: Direct buffer memory | Direct memory | NIO buffers outgrew -XX:MaxDirectMemorySize; they are freed by the garbage collector, so a leak can be delayed collection |
| CodeCache is full. Compiler has been disabled. | Code cache | JIT output filled its budget and the JVM falls back to interpreting hot code |
Read the error as an address. Each message points at one area in the map, and each area has one flag family that governs it.
StackOverflowError is not a heap problem
Deep recursion exhausts the JVM stack of one thread, so the fix is a smaller recursion depth or a larger -Xss, and every other thread keeps running meanwhile. Raising -Xmx changes nothing, because the stack and the heap are different areas with different owners. Name the area before you touch the flag; otherwise you have made the heap bigger and the bug identical.
Interview angles
Name the three subsystems of the JVM and what each one owns.+
The class loader subsystem finds and prepares classes, the runtime data areas hold all state (per-thread frames, plus the shared heap and class metadata), and the execution engine interprets, compiles and manages memory while executing bytecode.
Every runtime symptom maps onto one of the three: a missing class belongs to the loader, an OutOfMemoryError belongs to an area, a slow cold start belongs to the engine. That mapping is the real value of the model, more than the names themselves.
Common misconception: That the JVM is a single program you install. A specification defines the required behaviour, and several implementations satisfy it.
Follow-up: Which of those areas are per-thread?
Why is the JVM called a stack machine?+
Bytecode instructions take their operands from an operand stack inside the current frame and leave results there; the instruction set has no named registers.
A stack machine keeps instructions small (no register numbers to encode), makes the bytecode trivially portable, and simplifies verification: the verifier can track stack shapes and types at every point in a method. A JIT is still free to map that stack onto physical CPU registers once it proves nothing observable depends on the difference.
Common misconception: That the JVM cannot use CPU registers. The hardware always uses registers; the bytecode format simply does not name them, and the implementation is free to.
Follow-up: Where do a method's arguments arrive?
What is inside a stack frame?+
An array of local variables, an operand stack, and a reference to the runtime constant pool of the method's class. One frame is pushed per invocation and discarded on return, normally or abruptly.
The locals array is indexed by slot: for an instance method slot 0 holds this, and long or double values occupy two consecutive slots. The operand stack has a fixed ceiling, max_stack, written into the Code attribute by javac and checked by the verifier.
static int expr(int i, int j) { int k = i + j * 2; // operands go on the stack, result comes back return k; }
Follow-up: How deep can the stack of frames grow?
Which memory areas are shared between threads, and which are private?+
Per thread: the PC register, the JVM stack and the native method stack. Shared: the heap, the method area (Metaspace in HotSpot), the code cache and direct memory.
The division explains the synchronization rules: state that only ever lives in frames needs no locking, which is why local variables are thread-confined by construction. State that moves to the heap needs a happens-before relationship before other threads may trust it.
Common misconception: That objects and variables live wherever the JIT finds convenient with no consequence. Optimizations exist, but the spec's model, objects in the heap and frames on stacks, is the one you reason about.
Follow-up: A String literal ends up in the constant pool. Which area is that?
Where does the method area live in modern HotSpot?+
In Metaspace, which is native memory outside the heap, since Java 8. The JVMS defines the method area by what it must hold (class metadata, constant pools, method code); HotSpot chooses the storage.
Before Java 8 the same metadata lived in PermGen, inside the heap and sized with -XX:MaxPermSize. Moving it to native memory removed a class of heap tuning problems and introduced a different failure mode: metaspace growth caused by class loader leaks.
Follow-up: What happens to metadata when a class loader becomes unreachable?
The same .class file runs on a laptop and a server. How?+
The class file targets a virtual machine rather than a CPU: the spec defines the instruction set and the required behaviour, and each implementation supplies the platform adaptation. The JIT turns the hot parts into machine code for the CPU at hand, at runtime.
That is the whole portability bargain: compile once to a stable intermediate format, then let the runtime specialize it per platform. The cost is warm-up, which the Execution Engine & JIT lesson measures and mitigates.
Common misconception: That bytecode is machine code in disguise, or that the same native code runs everywhere. It is neither: it is a portable instruction set that gets compiled per run, per platform.