JVM Architecture: Inside the Java Virtual Machine
A deep dive into the JVM architecture covering Class Loader, Runtime Data Areas, and Execution Engine components that power Java applications.
A deep dive into the JVM architecture covering Class Loader, Runtime Data Areas, and Execution Engine components that power Java applications.
JVM Architecture: Inside the Java Virtual Machine
Introduction
The Java Virtual Machine runs Java bytecode and manages memory, class loading, and execution. Its architecture becomes useful when you investigate memory errors, GC behavior, class-loading problems, or JIT compilation.
This article introduces three JVM areas: class loading, the run-time data areas, and execution. HotSpot implementation examples refer to JDK 25; other JVMs can organize these internals differently.
When to Use This Knowledge
JVM internals help when you investigate OutOfMemoryError, GC behavior, class-loading failures, or performance changes under load. Start with application metrics and logs; inspect JVM internals when they help explain a measured problem.
Many applications can start with the JVM’s defaults. Validate those defaults under a representative workload, especially when you have strict memory or latency limits.
When NOT to Use This Knowledge
You do not need to study every JVM subsystem before building an application. The relevant detail depends on the problem you are investigating.
Successful startup and the absence of visible pauses do not show that memory use, throughput, or latency meet your service goals. Use production-like measurements before deciding whether tuning or deeper investigation is needed.
For a structured path through JVM topics, see the Advanced Java & JVM Internals roadmap.
JVM Architecture Diagram
The JVM consists of three main subsystems that work in concert to execute Java bytecode:
graph TD
subgraph "Class Loader Subsystem"
BL[Bootstrap Class Loader]
PL[Platform Class Loader]
CL[System / Application Class Loader]
BL --> PL
PL --> CL
CL --> JL[JVM Language Engines]
end
subgraph "Runtime Data Areas"
HEAP[Heap Memory]
MAS[Method Area]
JVMStack[JVM Stack]
PCR[PC Register]
NMS[Native Method Stack]
end
subgraph "Execution Engine"
INT[Interpreter]
JIT[JIT Compiler]
GC[Garbage Collector]
NMI[Native Method Interface]
end
JL -->|Loads Bytecode| RuntimeDataAreas
RuntimeDataAreas -->|Executes| ExecutionEngine
ExecutionEngine -->|Native Ops| NMI
NMI -->|Feedback| JIT
JIT -->|Optimized Code| ExecutionEngine
Core Components Explained
Class Loader Subsystem
The Class Loader handles loading, linking, and initializing class files. It works in three phases:
Loading finds a class’s binary representation by name. The built-in loaders are the bootstrap loader, platform loader, and system (application) loader. Since JDK 9, the platform loader replaced the older extension-loader role, and runtime classes are stored in the modular runtime image rather than rt.jar.
Linking verifies the class file, prepares class data, and may resolve symbolic references. Verification enforces class-file and type-safety rules; it does not sandbox code or guarantee that verified code cannot crash the process.
Initialization executes the class and interface initialization methods, including static field assignments and static blocks.
The default ClassLoader.loadClass strategy checks already-loaded classes, asks the parent, then calls findClass. Custom loaders can change the strategy, and module layers can assign modules to one or more loaders. Parent-first delegation is a common loading pattern, not a security boundary for untrusted code.
Runtime Data Areas
These are the memory regions the JVM uses during execution:
Heap Memory stores objects and arrays and is shared across threads. Garbage collectors manage the heap; its organization into generations or regions depends on the selected collector.
Method Area is a shared, specification-defined area for per-class structures such as run-time constant pools and method data. Its physical layout is implementation-specific. In HotSpot, class metadata uses native-memory Metaspace, while JIT-compiled native code uses a separate code cache. HotSpot’s older PermGen implementation was removed in JDK 8.
JVM Stack is per-thread. Each thread has its own JVM stack that stores frames. Each frame contains local variables, operand stack, and reference to the runtime constant pool of its class.
PC Register is also per-thread. It holds the address of the current instruction for non-native methods.
Native Method Stack is per-thread and supports native method execution, storing native method calls rather than Java bytecode.
Execution Engine
The Execution Engine reads and executes instructions from the Runtime Data Areas:
Interpreter reads bytecode and executes it instruction by instruction. It starts quickly but executes slowly because each instruction requires interpretation overhead.
JIT Compiler (Just-In-Time) solves the interpretation bottleneck. Hot methods, or code executed frequently, get compiled to native machine code at runtime. The JVM monitors which methods are “hot” based on invocation counts. Once compiled, calls to that method go directly to the native code, skipping interpretation.
Garbage Collector reclaims memory occupied by unreachable objects. Available collectors depend on the JVM and JDK version; HotSpot options include Serial, Parallel, G1, and ZGC.
Native Method Interface (JNI) allows Java code to interoperate with native applications and libraries written in C, C++, or assembly.
Production Failure Scenarios
Here are the most common ways the JVM breaks in production:
| Failure Scenario | Root Cause | Symptoms | Resolution |
|---|---|---|---|
| OutOfMemoryError: Heap Space | Memory leak or excessive allocation | Application slows, eventually crashes | Heap dump analysis, -Xmx tuning |
| OutOfMemoryError: Metaspace | Class loader leak or dynamic class generation | PermGen equivalent errors in Java 8+ | Increase Metaspace size, audit classloaders |
| ClassNotFoundException | Missing dependency or classloader hierarchy issue | Application fails to start or load feature | Check classpath, verify manifest, analyze classloader chain |
| StackOverflowError | Excessive recursion | Threads die with stack trace | Fix recursive code, increase -Xss |
| JIT Compilation Errors | Bytecode corruption or JVM bug | Sporadic crashes in optimized code | Disable JIT with -Xint, upgrade JVM |
| GC Thrashing | Heap too small, short-lived objects overwhelming GC | High CPU usage, application pauses | Increase heap, optimize object allocation patterns |
Trade-off Analysis
When designing systems that run on the JVM, you trade off competing concerns:
| Trade-off | Considerations |
|---|---|
| Heap Size vs. GC Pause | A larger heap may reduce collection frequency, but its effect on pauses depends on the collector and workload. Measure before changing heap limits. |
| Throughput vs. Latency | Parallel GC favors throughput. G1 and ZGC offer latency-oriented behavior, but observed pauses still depend on the workload and configuration. |
| Startup Time vs. Performance | Interpreted execution starts faster but runs slower. JIT warmup improves performance but takes time. Tiered compilation balances both. |
| Memory Footprint vs. Performance | Heap, Metaspace, code cache, and thread stacks all use process memory; monitor them together against the container or host limit. |
| Loading Strategy vs. Flexibility | Parent-first loading is the default for many class loaders. Plugin systems and module layers can use different loader arrangements. |
Failure Scenarios Deep Dive
JVM Crash with hs_err Log
When the JVM crashes, it writes an hs_err_pid<pid>.log file to the working directory before going down. Think of it as the JVM’s final selfie — everything in the process address space frozen at the moment of death. This is almost always more useful than an OS-level core dump for JVM-specific issues.
The log has a few parts worth knowing. The header at the top lists JVM version, startup flags, and OS info — useful when you inherit a server and no one remembers what was set. The “Current thread” section is where you start: it shows the crashing thread’s stack trace, and the top non-JVM frame is usually the culprit. The register state tells you exactly which instruction faulted. The memory map (near the bottom) shows which library owns which address range — if the fault address falls inside something you deployed, that’s your lead. The “VM abort” line at the end states the signal and address.
The most common real-world causes: a native library with a version mismatch (JNI code gets loaded once at startup, so a swap-out during deployment breaks things), improper JNI locking (releasing a critical section in the wrong order), and OS-level resource exhaustion — especially file descriptor limits on heavy I/O workloads. Hardware faults happen too, but less often.
One gotcha: if the log ends with “JVM internal signal handling” and no clear faulting frame, the crash is a secondary failure — something else broke first. Add -XX:ErrorFile=/var/log/myapp/hs_err.log so the file lands somewhere you can find it later.
Metaspace Exhaustion Without OOM
HotSpot replaced PermGen with Metaspace in JDK 8 and stores class metadata in native memory. If the JVM cannot allocate more metadata, it may throw OutOfMemoryError: Metaspace. An operating system or container can also terminate the process when total memory reaches its limit.
On Linux, HotSpot can detect container memory and CPU limits for resource ergonomics. That does not remove the need to budget total process memory: heap, direct buffers, Metaspace, code cache, thread stacks, JNI allocations, and other native memory all count against the container limit.
On Linux, pmap -x <pid> shows process memory mappings. If Native Memory Tracking was enabled at JVM startup, jcmd <pid> VM.native_memory summary can show HotSpot’s tracked memory categories. NMT does not account for every allocation made by native libraries, so compare its output with operating-system or container metrics.
Applications that generate classes dynamically, such as proxy or bytecode-generation frameworks, can increase metadata use. Frequent creation of class loaders can also prevent classes from being unloaded. Track the trend before changing Metaspace limits.
JIT Code Cache Exhaustion
HotSpot’s code cache is a separate non-heap area that holds generated native code. If the cache is full, the JVM may be unable to compile additional methods, and it reports this in diagnostic output. Exact behavior depends on the JVM and its code-cache configuration.
Reduced or stalled compilation can affect throughput, but a slowdown after warmup can also come from GC, workload changes, or application behavior. Check compilation and workload data before treating code-cache pressure as the cause.
Use jcmd <pid> Compiler.codecache to inspect the code-cache layout and bounds. Compilation logs can help confirm whether the JVM is still compiling methods. Available commands and defaults vary by JDK version.
-XX:ReservedCodeCacheSize controls the maximum code-cache size in HotSpot. Defaults depend on the JDK and compilation settings, so inspect the running JVM before changing this option. Code-cache size is separate from the Metaspace limit.
Implementation Patterns
These patterns show how the JVM loads and executes code:
// Demonstrating classloader hierarchy
public class ClassLoaderDemo {
public static void main(String[] args) {
ClassLoader loader = ClassLoaderDemo.class.getClassLoader();
int level = 0;
while (loader != null) {
System.out.println("Level " + level + ": " + loader.getClass().getName());
loader = loader.getParent();
level++;
}
// Loader names vary by JVM; the bootstrap loader is commonly represented as null.
}
}
Custom loaders can change parent-first lookup, and module layers can map modules to one loader, separate loaders, or caller-provided loaders. A loader is a class-loading mechanism; it does not isolate untrusted code from the process.
Observability Checklist
Track these key metrics to monitor JVM health:
- Heap usage: Monitor used vs. committed vs. max heap. Watch for steady growth indicating potential leaks.
- Metaspace usage: Track committed and used metaspace. Classloader leaks appear as growth without collection.
- GC metrics: Examine collection frequency, duration, and garbage generated. Compare young vs. old generation behavior.
- JIT compilation: Monitor compiled methods count, compilation time, and code cache usage.
- Thread counts: Track daemon vs. non-daemon threads, especially for applications using thread pools.
- Class loading: Watch classes loaded vs. unloaded counts over time.
Enable these flags for production diagnostics:
# Heap dump on OOM
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/myapp/
# GC logging
-Xlog:gc*:file=/var/log/myapp/gc.log:time,uptime,level,tags
# Class loading trace
-Xlog:class+load=info,class+unload=info
# JIT compilation logging
-XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly
Security Notes
Class-file verification, class loading, and modules support JVM execution and encapsulation, but they do not provide a sandbox for untrusted code.
Class-file verification checks structural and type-safety rules before code runs. It does not prevent verified code from exhausting resources, throwing exceptions, or otherwise disrupting the process.
Class-loader delegation describes how a loader searches for classes. Custom loaders can use different lookup rules, so delegation is not an isolation boundary.
Modules control readability and which packages are exported or opened to other modules. They help encapsulate APIs, but do not confine hostile code.
The Security Manager was permanently disabled in JDK 24. If an application must execute untrusted code, run it in a separate operating-system process and apply least-privilege OS or container controls for files, network access, and resource limits.
Common Pitfalls / Anti-Patterns
Watch out for these frequent mistakes when working with JVM internals:
Assuming heap is the only memory region. Many developers fixate on heap size while ignoring Metaspace growth, direct buffer memory, JIT code cache, and thread stacks. Native memory exhaustion causes OOM even with plenty of heap available.
Ignoring GC ergonomics. Modern JVMs auto-tune GC based on workload. Overly aggressive tuning can backfire. Let the JVM’s adaptive ergonomics work before manually setting GC parameters.
Misunderstanding classloader scope. Each classloader defines a namespace. A class loaded by one classloader is different from the same class loaded by a different classloader. This causes ClassCastException when passing objects between code loaded by different classloaders.
Treating String.intern() as free. Interning canonicalizes equal strings, but it does not reduce the cost of creating or retaining too many distinct strings. Measure the workload before adding interning.
Forgetting about finalization. Objects with finalize() methods linger longer because the GC must invoke finalizers before reclaiming them. Avoid relying on finalize for cleanup. Use try-with-resources or Cleaner instead.
Quick Recap Checklist
Use this checklist when reviewing JVM-related code or troubleshooting:
- Heap limits measured against workload and total process/container memory
- Metaspace size configured if using dynamic class generation
- GC algorithm matches workload characteristics (throughput vs. latency requirements)
- GC logs enabled and monitored for patterns
- Heap dump flags set for OOM incident investigation
- Thread stack size adequate for recursive depth needs
- Classloader hierarchies understood for modular applications
- Native memory tracked alongside heap metrics
- JIT compilation logs reviewed if investigating performance anomalies
- Module encapsulation understood as an API boundary, not a sandbox for untrusted code
Interview Questions
The JVM consists of three primary subsystems: Class Loader which loads bytecode files and resolves symbolic references; Runtime Data Areas which provide the memory regions for storing loaded classes, objects, stacks, and registers during execution; and Execution Engine which interprets bytecode, JIT compiles hot paths to native code, and runs the garbage collector.
Current JDKs provide the bootstrap, platform, and system (application) class loaders. Since JDK 9, the platform loader fills the older extension-loader role, and the runtime image no longer contains rt.jar. The ClassLoader API commonly represents the bootstrap loader as null.
The Just-In-Time compiler solves the interpretation overhead problem by identifying "hot" code paths—methods invoked frequently or loops that run many iterations—and compiling them to native machine code at runtime. Once a method is JIT-compiled, calls to it bypass the interpreter entirely and execute as native instructions. The JVM uses profiling data to make intelligent optimization decisions, like inlining methods, eliminating bounds checks, and removing dead code. This gives JIT-compiled code performance approaching statically compiled languages while maintaining Java's platform independence.
The heap stores objects and arrays. Its organization depends on the collector. The JVMS defines the Method Area as an abstract shared area for per-class data; it does not prescribe a physical memory layout. In HotSpot, Metaspace stores class metadata in native memory, while the separate code cache stores JIT-generated native code. Both can contribute to process memory pressure outside the Java heap.
The default ClassLoader.loadClass checks whether a class is already loaded, asks the parent loader, then calls findClass. A custom loader may override that strategy, and module layers can use different loader arrangements. Parent-first delegation is a common loading rule; it does not sandbox code or make an application safe to run untrusted classes in-process.
The JVM makes optimistic assumptions during JIT compilation—for example, that a particular method will always be called on objects of a specific type, or that a branch will always go a certain direction. When these assumptions are violated (a new subclass is loaded, an uncommon branch is taken), the JVM performs deoptimization: it marks the compiled code as invalid and falls back to interpreted mode. The method will be recompiled with updated profiling data if it remains hot. Deoptimization can cause performance hiccups known as "deoptimization storms" when frequent class loading or type changes affect heavily optimized code.
The JVM was designed to be implementation-agnostic and easily portable to hardware architectures with varying register counts. A stack-based bytecode is simpler to generate and verify, making it easier to port the JVM to new platforms. Additionally, stack-based instructions are more compact (no register specifiers in the instruction encoding), reducing class file sizes. The tradeoff is that register-based native code could theoretically be faster on register-rich architectures, but modern JIT compilers perform register allocation during native code generation, recovering most of that performance.
Interpretation provides immediate startup with no compilation overhead—bytecode begins executing instantly but each instruction requires a lookup and dispatch cycle, making it slower for long-running code. JIT compilation incurs upfront compilation cost (the "warmup" period), but once code is compiled, it runs at near-native speed without interpreter overhead. The JVM uses tiered compilation to balance both: interpreted code runs immediately while hot methods are queued for JIT compilation. After warmup, the application reaches peak performance. For short-running programs or tools, interpretation may actually be faster since JIT costs would dominate.
The JVM profiles executing code to identify hot methods and call sites. Each time a method is invoked, an invocation counter increments. When the count exceeds a threshold (controlled by -XX:CompileThreshold, defaulting to around 10,000 invocations), the method becomes eligible for JIT compilation. The JVM also tracks branch frequency at call sites—if a particular branch is taken thousands of times, that path gets optimized. Additionally, the JIT monitors "on-stack replacement" opportunities where a frequently looped method can be compiled mid-execution. Profiling data feeds optimization decisions like inlining, dead code elimination, and speculative type guards.
In HotSpot, the code cache is a non-heap memory area for JIT-generated native code, separate from Metaspace. A full cache can prevent additional compilation. Use jcmd <pid> Compiler.codecache to inspect its layout; size defaults and diagnostic commands vary by JDK.
Tiered compilation uses multiple compilation levels to balance startup speed against peak performance. Tier 1 is interpreted bytecode with immediate execution but slowest speed. Tier 2 uses the client JIT compiler (C1) for quick native code generation with basic optimizations. Tier 3 applies more aggressive profiling-based optimizations from the server compiler. Tier 4 delivers fully optimized native code with maximum performance. Methods move up tiers as they accumulate invocation counts. This approach avoids the delay of waiting for full server compilation while still achieving high performance for sustained hot methods.
Direct ByteBuffers allocate native memory outside the heap through ByteBuffer.allocateDirect(). This memory is managed by the OS, not the JVM GC, and is released when the ByteBuffer is garbage collected—but only after a cleaner (added automatically in Java 9+) or explicit Unsafe invocation triggers native deallocation. If applications create many short-lived direct buffers without proper cleanup, native memory can accumulate and cause OOM even when heap has space. The -XX:MaxDirectMemorySize flag limits direct buffer allocation. NMT (Native Memory Tracking) via jcmd helps diagnose direct buffer memory pressure.
An hs_err log is a JVM-generated error file created when the JVM encounters a fatal error (segmentation fault, stack overflow in native code, etc.). It contains JVM state: register values, thread stacks, memory regions, and often the immediate cause of the crash. It is specific to JVM crashes and includes JVM internal details. A core dump is an OS-level memory snapshot of the entire process, including native heap, stack, and all memory regions. Core dumps are larger and require OS tools to analyze, but they capture the complete process state. For JVM crashes, the hs_err log is usually more immediately useful, but core dumps are needed when the hs_err log does not provide enough detail.
HotSpot can encode class pointers in a compressed form when the VM configuration permits it. This can reduce object-reference overhead; it does not halve Metaspace usage. The exact range depends on heap layout and options, so inspect the flags for the JDK and architecture you deploy.
-Xms sets the initial heap size and -Xmx sets the maximum. Matching them can avoid heap resizing, but it also commits the process to a larger memory budget. Choose values from workload measurements and leave room for Metaspace, code cache, thread stacks, direct buffers, and other process memory.
GraalVM uses a single compiler (Graal) written in Java itself, replacing C1 and C2 which are written in C++. This makes Graal easier to extend, debug, and optimize. Graal supports aggressive optimizations like partial escape analysis beyond what C2 offers. It also enables Truffle, a framework for building language implementations, allowing polyglot execution where JavaScript, Python, and other languages call Java and vice versa. GraalVM can operate as an Ahead-of-Time (AOT) compiler, compiling bytecode to native executables for faster startup with reduced memory overhead, useful for serverless and microservice deployments.
Each JVM instance runs as a single operating system process. The OS schedules JVM threads as it would any threads—they compete for CPU time, share system resources, and are subject to OS-level memory management. The JVM does not create new processes for threads; all Java threads map to native threads (1:1 model in HotSpot). This means OS-level resource limits (file descriptors, memory limits, process permissions) directly constrain the JVM. A thread stack overflow at the OS level causes a segmentation fault, while a JVM StackOverflowError results from the JVM detecting the stack has exceeded its configured depth. Understanding this mapping helps when debugging native memory issues or OS-level resource exhaustion.
The Java Virtual Machine Specification defines the abstract machine: its instruction set, data types, memory model, class file format, and runtime behavior. It is the contract that all JVM implementations must follow. This specification enables Java's "write once, run anywhere"—code compiled to bytecode runs on any JVM that correctly implements the spec, whether HotSpot, OpenJ9, or Graal. The JVMS also defines verification rules, the meaning of bytecode instructions, and the semantics of class loading and initialization. Implementers use it as a reference; developers use it to understand why certain code behaves as it does at the JVM level.
Inlining replaces method calls with the method body to eliminate call overhead and enable cross-method optimizations. At Tier 1 (interpreted), no inlining occurs. At Tier 2 (C1), the compiler inlines small methods and frequently-called sites with basic profiling. At Tier 4 (C2/server), aggressive inlining applies based on call frequency, method size, and the ability to inline across module boundaries with @ForceInline and @DontInline hints. Inlining decisions are subject to the inline budget—too much inlining increases code cache pressure. C2 uses type profiling and devirtualization to enable inlining of interface calls when the concrete type is predictable.
When the JVM exhausts a managed region (heap, Metaspace), it throws OutOfMemoryError with a descriptive message indicating which region was exhausted (e.g., "Java heap space", "Metaspace"). This is a Java exception the application can catch and handle. When the operating system denies memory to the JVM process—for example, when native memory is exhausted or container memory limits are hit—the JVM may crash with a SIGKILL or generate an hs_err log reporting memory allocation failures. The distinction matters for debugging: OOM in managed memory usually indicates application-level issues (leaks, excessive allocation), while OS-level memory denial requires investigating system limits, container boundaries, or native memory leaks in JNI code.
Further Reading
- Class Loader Subsystem - Deep dive into loading, linking, and initialization
- Runtime Data Areas - Heap, stack, and Metaspace internals
- Execution Engine - Interpreter, JIT, and garbage collection
- JVM Bytecode Verification - Type safety and the verification process
- JVM Startup and Shutdown - Bootstrap sequence and shutdown hooks
- Advanced Java & JVM Internals Roadmap - Structured learning path for JVM mastery
- Java 27
ClassLoaderAPI - Built-in loaders and the default delegation strategy - JDK migration guide - The platform loader and removal of
rt.jar - Java Virtual Machine Specification, section 2 - Abstract run-time areas and class-file rules
- Security Manager permanently disabled - JDK 24+ status and OS-level isolation alternatives
- JDK 27
jcmdreference - Diagnostic commands includingCompiler.codecache
Conclusion
The JVMS defines the logical runtime areas, while HotSpot supplies implementation details such as Metaspace and the code cache. Parent-first loading is common, but custom loaders and module layers can change lookup behavior. Verification and modules are not sandboxes; isolate untrusted code with operating-system process or container controls.
Category
Related Posts
Class Loader Subsystem: Loading, Linking, and Initialization
Deep dive into the JVM Class Loader subsystem covering loading, linking, initialization phases and the ClassLoader hierarchy with parent delegation model.
Java Flight Recorder: Continuous Monitoring and Diagnostics
Learn Java Flight Recorder setup, storage limits, overhead measurement, and practical analysis with Oracle JDK 25 and JMC 9.1.2.
JIT Compilation Internals
See how HotSpot tiered compilation works in JDK 25, how to inspect warmup, and when JFR or compilation logs can guide tuning.