- Prerequisites
- 1.1 What Is the JVM?
- Covers
- Class Loader Subsystem · Runtime Data Areas · Execution Engine · Native Interface · Native Method Libraries
- Related
- Chapter 2 (class loaders) · 4.5 Operand Stack · 5.5 Execution Engine · Book 2 Volume II (memory & GC)
On this page
1Concept / Definition
A JVM is organised into five cooperating parts. The Class Loader Subsystem finds, loads, links and initialises classes. The Runtime Data Areas hold everything the program needs while running: heap, method area (Metaspace), per-thread stacks and PC registers. The Execution Engine runs bytecode through an interpreter and JIT compilers and reclaims memory with the garbage collector. The Java Native Interface and the FFM API connect Java code to native code, which lives in native method libraries.

| Component | Responsibility | Main failure modes | Covered in |
|---|---|---|---|
| Class Loader Subsystem | loading, linking, initialisation | ClassNotFoundException, NoClassDefFoundError, LinkageError | Chapters 2–3 |
| Runtime Data Areas | storage of objects, metadata, frames | OutOfMemoryError (various), StackOverflowError | Book 2 Volume II |
| Execution Engine | interpretation, JIT, GC | deoptimisation storms, GC pauses, code cache full | Chapter 5, Volume II |
| Native Interface | calls between Java and native code | UnsatisfiedLinkError, JVM crashes | this note |
| Native Libraries | OS and JDK native code | crashes, native leaks | this note |
2Why It Exists
Each component addresses a distinct problem: getting code in safely (loaders and verifier), storing program state with the right lifetime and sharing semantics (runtime areas), executing fast while staying portable (interpreter plus JIT), managing memory automatically (GC), and reaching the operating system (native interface). Knowing which component owns a behaviour tells you where to look when something fails — an error message almost always identifies the component involved.
3Core Concepts
Class Loader Subsystem
Phases
- Loading — a class loader locates the binary representation (jar entry,
jrt:/module image, generated bytes) and the JVM parses it into internal class metadata plus ajava.lang.Classobject. - Linking — verification (type-safety of bytecode), preparation (static fields allocated with default values), resolution (symbolic references replaced by direct ones, usually lazily).
- Initialisation — static initialisers and static field assignments (
<clinit>) run, triggered by first active use.
Loaders
Three built-in loaders — bootstrap, platform and application — form a delegation hierarchy; applications and frameworks add custom loaders for isolation and dynamic code (Chapter 2). Each loaded class is identified by its name and its defining loader.
Runtime Data Areas

| Area | Scope | Contents | HotSpot realisation |
|---|---|---|---|
| Heap | shared | objects, arrays | generational / region-based GC heap |
| Method area | shared | class metadata, code, constant pools | Metaspace (native memory) |
| Run-time constant pool | per class | literals, symbolic references | part of class metadata |
| JVM stack | per thread | frames: locals, operand stack | OS thread stack |
| PC register | per thread | current instruction | interpreter register / return addresses |
| Native method stack | per thread | native frames | same OS thread stack |


Beyond the specification's areas, a real JVM process also uses a code cache for compiled code, GC data structures, symbol tables, thread structures and direct buffers — all native memory counted against container limits (Volume II 1.6).

Execution Engine
Interpreter
HotSpot's template interpreter executes bytecode immediately using pre-generated machine-code templates for each instruction. It also collects profiles — invocation and loop counters, branch frequencies, receiver types — that guide later compilation.
JIT compilers (tiered compilation)
| Tier | Executed by | Purpose |
|---|---|---|
| 0 | interpreter | start immediately; profile |
| 1 | C1, no profiling | trivial methods |
| 2–3 | C1 with (limited/full) profiling | fast compilation while collecting profiles |
| 4 | C2 | aggressive optimisation: inlining, escape analysis, vectorisation, speculation |
C2 speculates based on profiles (e.g. a call site only ever sees one receiver type). If an assumption is later violated, the JVM deoptimises: compiled frames are converted back to interpreter frames and the method may be recompiled.
Garbage collector
Part of the execution engine in the classic diagram: it reclaims heap memory of unreachable objects and cooperates with compiled code through barriers and safepoints (Volume II). Choice of collector — G1 (default), ZGC, Parallel, Serial — shapes pause times and throughput.

JVM-internal threads

Native Interface
- JNI — the classic mechanism:
nativemethods bound to C functions (Java_pkg_Class_methodorRegisterNatives), access to Java objects viaJNIEnv, local and global references. - FFM API (final in Java 22) — calls native functions through
Linkerdowncall handles and manages native memory withArena/MemorySegment; no C glue code needed. - Both switch the thread into *native* state; GC can proceed without waiting for it.
- Since Java 24 (JEP 472), JNI and restricted FFM methods produce warnings unless native access is enabled with
--enable-native-access.

Native Method Libraries
- JDK natives —
libjava,libnio,libnet,libzip,libjvmitself; they implement file and socket I/O, compression and much ofjava.base's low-level behaviour. - Application natives — Netty's epoll/io_uring transports, compression (zstd, lz4), crypto providers, database drivers, image processing.
- Loaded with
System.loadLibrary/System.load(JNI) orSymbolLookup.libraryLookup(FFM); must match OS and CPU architecture. - Bugs in native code crash the whole JVM (
hs_err_pid<pid>.log) and native memory is invisible to heap tools.
4How It Works Internally
How the components cooperate
- The launcher creates the JVM; bootstrap loads
java.baseclasses (mostly from the CDS archive). - The application loader loads the main class; linking verifies it; initialisation runs
<clinit>. - The interpreter executes
main, allocating objects in the heap and frames on the thread stack. - Hot methods are compiled by C1 and C2 into the code cache; later calls jump to compiled code.
- The GC periodically reclaims heap memory, pausing threads at safepoints or working concurrently.
- Calls to native methods leave the managed world through JNI/FFM stubs and return.

5APIs / Features / Syntax
# Looking at each component of a live JVM
$ jcmd <pid> VM.classloaders # class loader subsystem: loader tree
$ jcmd <pid> VM.metaspace summary # method area / Metaspace
$ jcmd <pid> GC.heap_info # heap
$ jcmd <pid> Thread.print # stacks of all threads (incl. JVM threads)
$ jcmd <pid> Compiler.codecache # code cache usage
$ jcmd <pid> Compiler.queue # pending JIT compilations
# native memory by component (needs -XX:NativeMemoryTracking)
$ jcmd <pid> VM.native_memory summary
$ java -XX:+PrintCompilation -jar app.jar # JIT events as they happen// Runtime view from inside the application
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
log.info("VM {} {} by {}", rt.getVmName(), rt.getVmVersion(), rt.getVmVendor());
log.info("loaded classes: {}", ManagementFactory.getClassLoadingMXBean().getLoadedClassCount());
log.info("JIT: {} total compile time {} ms",
ManagementFactory.getCompilationMXBean().getName(),
ManagementFactory.getCompilationMXBean().getTotalCompilationTime());
ManagementFactory.getMemoryPoolMXBeans()
.forEach(p -> log.info("{} ({}) used={} KB",
p.getName(), p.getType(), p.getUsage().getUsed() >> 10));6Practical Examples
| Symptom | Component | First step |
|---|---|---|
| NoClassDefFoundError at startup | class loader subsystem | -Xlog:class+load, check class path/versions |
| OutOfMemoryError: Metaspace | runtime areas (method area) | class counts, loader leaks |
| StackOverflowError | runtime areas (JVM stack) | recursion depth, stack trace |
| CPU spike after deployment, then settles | execution engine (JIT warm-up) | JFR compilation events |
| 'CodeCache is full. Compiler has been disabled' | execution engine (code cache) | raise ReservedCodeCacheSize, check class churn |
| JVM crash with hs_err in libfoo.so | native library | update/replace library; reproduce |
7Common Problems & Mistakes
- Treating every memory problem as a heap problem — Metaspace, code cache, stacks and native memory fail independently.
- Benchmarking without JIT warm-up — measuring the interpreter, not steady state.
- Adding JNI libraries for small speed-ups — crashes and native leaks outweigh gains; prefer pure Java or FFM.
- Disabling tiered compilation or JIT features based on outdated advice.
- Ignoring the code cache in applications that generate many classes.
8Performance & Production Considerations
- Warm-up: a new instance runs slower until hot methods are compiled; use readiness probes, gradual traffic shifting, or AOT cache/CDS to shorten it.
- Code cache: default
ReservedCodeCacheSizeis 240 MB with tiered compilation; a full code cache stops compilation and degrades performance silently. - Container limits: all components share the container's CPU and memory — JIT and GC threads compete with application threads.
- Native memory tracking and JFR give per-component visibility at low overhead.
9Architecture & Design Considerations
The component model explains architectural trade-offs of Java services: startup and warm-up costs (loading + JIT) influence autoscaling and serverless suitability; memory beyond the heap influences container sizing; native dependencies influence portability across CPU architectures (x64 vs ARM) and security posture. Architects should know which runtime components their design stresses — class generation, deep recursion, native libraries, huge heaps — and choose JVM options and implementations accordingly.
10Interview Questions & Answers
What are the main components of the JVM?
The JVM has five cooperating parts. The class loader subsystem finds, loads, links and initialises classes. The runtime data areas hold program state: the shared heap and method area, which HotSpot implements as Metaspace, plus a JVM stack, PC register and native method stack for each thread. The execution engine runs bytecode, first in the interpreter and then through the C1 and C2 JIT compilers, and includes the garbage collector. The native interface, JNI or the FFM API final since Java 22, connects Java code to native method libraries such as libjava and libnio. Knowing these parts matters because almost every runtime error points to exactly one of them.
Which runtime data areas are shared between threads?
The heap and the method area are shared by all threads. The heap holds every object and array, and the method area, Metaspace in HotSpot, holds class metadata, method bytecode and each class's run-time constant pool. Everything else in the specification is per thread: the JVM stack with its frames, the PC register and the native method stack. The practical consequence is that local variables are thread-confined, while any object reachable through a shared reference can be seen by several threads and needs proper synchronisation. Outside the specification, the code cache and GC data structures are also shared, and they live in native memory rather than in the heap.
What does the class loader subsystem do?
It turns class files into usable classes in three phases. Loading locates the bytes, from a JAR, the jrt module image or generated code, and creates a Class object. Linking verifies that the bytecode is type-safe, prepares static fields with default values and resolves symbolic references, usually lazily. Initialisation runs the static initialisers in <clinit> on first active use. Loaders form a delegation hierarchy of bootstrap, platform and application loaders, and frameworks add their own for isolation. A class is identified by its name plus its defining loader, so the same class loaded by two loaders gives two incompatible types, which explains many ClassCastException puzzles in plug-in systems.
Why does the JVM have both an interpreter and JIT compilers?
Because they solve opposite problems. The interpreter can execute any method the moment it is loaded, so startup is fast and no time is wasted compiling code that runs only once. While interpreting, it records invocation counts, branch frequencies and receiver types. The JIT compilers then spend effort only on hot methods and use those profiles to optimise aggressively, inlining the observed call targets and laying out the likely branches. Most code in a service never becomes hot, so this split gives quick startup and near-native peak performance. A pure ahead-of-time compiler would also start fast, but it could not speculate on real run-time behaviour in the same way.
What is tiered compilation?
Tiered compilation is HotSpot's default strategy of moving a method through levels of increasing optimisation. Tier 0 is the interpreter, which starts immediately and profiles. Tier 3 is C1 with full profiling, producing reasonably fast code quickly while still collecting data; tiers 1 and 2 are C1 variants used for trivial methods or when the C2 queue is busy. Tier 4 is C2, which uses the rich profile for inlining, escape analysis, vectorisation and speculation. The benefit is that code becomes fast early and then very fast. The cost is more code in the code cache and noticeable compiler CPU during warm-up, but it should simply be left enabled.
What is deoptimisation?
Deoptimisation is the JVM discarding compiled code whose assumptions no longer hold and continuing execution in the interpreter. C2 speculates from profiles, for example that a call site only ever sees one receiver type or that a branch is never taken, and compiles an uncommon trap for the other case. When a new subclass is loaded or an unexpected type arrives, the trap fires, compiled frames are rebuilt as interpreter frames from debug information, and the method is marked not entrant. It is later reprofiled and recompiled with the wider behaviour. Occasional deoptimisation is healthy; repeated cycles show up as unstable latency and are visible in JFR deoptimisation events.
What happens when the code cache fills up?
The JIT stops compiling. HotSpot logs 'CodeCache is full. Compiler has been disabled', existing compiled code keeps running, but any method that becomes hot afterwards stays interpreted, so throughput degrades gradually with no exception or crash. That silence is the trap. The default reservation is 240 MB with tiered compilation, which is plenty for most services, so a full cache usually signals churn: heavy dynamic class generation, proxies, scripting engines or repeated redeployments into the same JVM. Raise ReservedCodeCacheSize as the immediate fix, then find the source of churn with jcmd Compiler.codecache and class-loading metrics, and alert on CodeHeap usage in production.
What are the risks of JNI?
JNI trades JVM safety for access to native code. A bug in the native library, such as a bad pointer or buffer overrun, crashes the whole process with an hs_err file instead of throwing an exception. Native allocations are invisible to the GC and to heap dumps, so leaks show up only as growing RSS. Leaked global references pin Java objects, JNI calls cannot be inlined, and the library must be built for every OS and CPU, which complicates a move to ARM. Since Java 24, native access also produces warnings unless enabled with --enable-native-access. Prefer pure Java, and where native code is unavoidable, use the FFM API, which needs no C glue.
How would you diagnose a problem when you don't know which JVM component is involved?
Start from the symptom, because it almost always names the component. A NoClassDefFoundError or LinkageError points to class loading; the OutOfMemoryError message says whether it is heap, Metaspace or native threads; an hs_err file names the crashing library; a CPU spike after deployment suggests JIT warm-up. Then use the tool for that component: -Xlog:class+load, Native Memory Tracking for non-heap memory, GC logs and heap dumps, JFR compilation and GC events, and thread dumps for hangs. If the symptom is vague, a JFR recording plus an NMT summary gives a cheap view of every component at once, and comparing two snapshots shows what is growing.
Why does a freshly started Java service perform worse than one that has been running?
Because nothing is warm yet. Classes are still being loaded and initialised lazily on first use, and hot methods are interpreted or only C1-compiled while C2 waits for profiles. Compiler threads compete with request threads for CPU, which hurts most in small containers. Application caches, connection pools and the CPU's own caches are also cold. Latency improves over the first minutes as C2 compiles the hot paths. The fixes are operational: readiness probes that pass after warm-up, gradual traffic shifting or load-balancer slow start, synthetic warm-up requests, CPU headroom at startup, and class data sharing or the Java 25 AOT cache to cut loading and profiling time.
How does JVM architecture influence deployment architecture?
JVM behaviour sets several deployment constraints. Startup and warm-up costs decide how well a service suits aggressive autoscaling, scale-to-zero or serverless platforms. Memory outside the heap, such as Metaspace, code cache, thread stacks and direct buffers, must fit inside container limits, or the pod is OOM-killed while the heap looks healthy. JIT and GC threads need CPU, so tiny CPU quotas cause long warm-up and throttling. Native libraries tie images to an OS and CPU architecture. These factors drive choices such as instance size, heap percentage, collector, an AOT cache or GraalVM Native Image for fast start, and long-lived instances versus frequent restarts.
Test your knowledge on this topic →Flashcards from this topic's 11 questions, filtered by level and type.