ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 2 · JVM, Concurrency & Performance
  4. Volume I
  5. JVM Architecture
Book 2 · Volume I — JVM Architecture, Class Loading & Bytecode · Topic 1.2

JVM Architecture

Class Loader Subsystem, Runtime Data Areas, Execution Engine, Native Interface and Native Libraries

11 min readStage 1 · Foundations11 interview questions
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
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers

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.

The JVM's major components
Figure 1 — The JVM's major components
ComponentResponsibilityMain failure modesCovered in
Class Loader Subsystemloading, linking, initialisationClassNotFoundException, NoClassDefFoundError, LinkageErrorChapters 2–3
Runtime Data Areasstorage of objects, metadata, framesOutOfMemoryError (various), StackOverflowErrorBook 2 Volume II
Execution Engineinterpretation, JIT, GCdeoptimisation storms, GC pauses, code cache fullChapter 5, Volume II
Native Interfacecalls between Java and native codeUnsatisfiedLinkError, JVM crashesthis note
Native LibrariesOS and JDK native codecrashes, native leaksthis 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

  1. 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 a java.lang.Class object.
  2. Linking — verification (type-safety of bytecode), preparation (static fields allocated with default values), resolution (symbolic references replaced by direct ones, usually lazily).
  3. 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

Shared areas and per-thread areas
Figure 2 — Shared areas and per-thread areas
AreaScopeContentsHotSpot realisation
Heapsharedobjects, arraysgenerational / region-based GC heap
Method areasharedclass metadata, code, constant poolsMetaspace (native memory)
Run-time constant poolper classliterals, symbolic referencespart of class metadata
JVM stackper threadframes: locals, operand stackOS thread stack
PC registerper threadcurrent instructioninterpreter register / return addresses
Native method stackper threadnative framessame OS thread stack
Heap generations and Metaspace
Figure 3 — Heap generations and Metaspace
Frames on a thread's stack
Figure 4 — Frames on a thread's 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).

The code cache
Figure 5 — The code cache

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)

TierExecuted byPurpose
0interpreterstart immediately; profile
1C1, no profilingtrivial methods
2–3C1 with (limited/full) profilingfast compilation while collecting profiles
4C2aggressive 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.

Interpreter, JIT tiers, deoptimisation and GC
Figure 6 — Interpreter, JIT tiers, deoptimisation and GC

JVM-internal threads

Threads the JVM starts for itself
Figure 7 — Threads the JVM starts for itself

Native Interface

  • JNI — the classic mechanism: native methods bound to C functions (Java_pkg_Class_method or RegisterNatives), access to Java objects via JNIEnv, local and global references.
  • FFM API (final in Java 22) — calls native functions through Linker downcall handles and manages native memory with Arena/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.
From a Java call to native code
Figure 8 — From a Java call to native code

Native Method Libraries

  • JDK natives — libjava, libnio, libnet, libzip, libjvm itself; they implement file and socket I/O, compression and much of java.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) or SymbolLookup.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

  1. The launcher creates the JVM; bootstrap loads java.base classes (mostly from the CDS archive).
  2. The application loader loads the main class; linking verifies it; initialisation runs <clinit>.
  3. The interpreter executes main, allocating objects in the heap and frames on the thread stack.
  4. Hot methods are compiled by C1 and C2 into the code cache; later calls jump to compiled code.
  5. The GC periodically reclaims heap memory, pausing threads at safepoints or working concurrently.
  6. Calls to native methods leave the managed world through JNI/FFM stubs and return.
Each area has its own failure mode
Figure 9 — Each area has its own failure mode

5APIs / Features / Syntax

SHELLOne command per architectural component
# 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
JAVAComponent metrics via JMX
// 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

SymptomComponentFirst step
NoClassDefFoundError at startupclass loader subsystem-Xlog:class+load, check class path/versions
OutOfMemoryError: Metaspaceruntime areas (method area)class counts, loader leaks
StackOverflowErrorruntime areas (JVM stack)recursion depth, stack trace
CPU spike after deployment, then settlesexecution 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.sonative libraryupdate/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 ReservedCodeCacheSize is 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

Q1L1 · BasicConcept

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.

Q2L1 · BasicConcept

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.

Q3L2 · IntermediateInternals

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.

Q4L2 · IntermediateConcept

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.

Q5L3 · Senior EngineerInternals

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.

Q6L3 · Senior EngineerInternals

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.

Q7L3 · Senior EngineerTricky

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.

Q8L3 · Senior EngineerTrade-off

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.

Q9L4 · Technical ArchitectScenario

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.

Q10L4 · Technical ArchitectScenario

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.

Q11L5 · Solution ArchitectDesign

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.