Understanding the JVM: How It Works Under the Hood
On this page
- 1. Introduction
- 2. The JVM as a Process (Linux Process Memory Model)
- What each segment contains for the JVM process
- Key insight: the Java heap is a subset of the process's virtual memory
- 3. JVM Memory Areas
- 3.1 Java Heap (GC-Managed, Shared Across All Threads)
- 3.2 Metaspace (Native Memory, NOT on the Java Heap)
- 3.3 CodeCache (Native Memory)
- 3.4 Thread Stacks (Native Memory)
- 3.5 Direct Memory (Native Memory)
- 3.6 Internal VM Data (Native Memory)
- 4. Java Threads
- 4.1 Threading Model
- 4.2 Thread Lifecycle (Inside the JVM)
- 4.3 Per-Thread Components
- 5. JVM System Threads
- VM Thread
- GC Threads
- Compiler Threads
- Periodic Task Thread
- Signal Dispatcher Thread
- Service Thread
- 6. Shared Memory Areas and Thread Safety
- Class Loading is Thread-Safe
- Constant Pool Resolution is Synchronized
- Heap Access and the Java Memory Model
- 7. Class Loading Subsystem
- 7.1 Loading
- 7.2 Linking
- 7.3 Initialization
- 7.4 Unloading
- 7.5 Worked Example: Tracing Class Loading Through All Phases
- 8. The Execution Engine
- 8.1 The Template Interpreter
- 8.2 JIT Compilation (Tiered Compilation)
- 8.3 On-Stack Replacement (OSR)
- 8.4 Deoptimization
- 8.5 GraalVM and Alternatives
- 9. Garbage Collection in Java 17
- 9.1 The Generational Hypothesis
- 9.2 TLAB (Thread-Local Allocation Buffers)
- 9.3 G1 GC (Default Since Java 9)
- 9.4 Other Collectors Available in Java 17
- 10. Putting It All Together: Complete Walkthrough
- Phase 1: Loading
- Phase 2: Linking Main
- Phase 3: Initializing Main
- Phase 4: Executing main()
- Phase 5: Garbage Collection
- Phase 6: JIT Compilation (Hypothetical Hot Loop)
- 11. Key JVM Flags for Java 17 (Reference Table)
- Heap Sizing
- Metaspace
- Thread Stack
- Garbage Collection
- CodeCache
- Direct Memory
- JIT Compilation
- Diagnostics and Debugging
- Practical Starter Configuration
- Conclusion
- Looking Ahead: Java 21 and Beyond
1. Introduction
I came into software from mechanical engineering. My first real language was C - pointers, manual memory management, malloc and free, the whole thing. I loved it. There's something deeply satisfying about knowing exactly what the machine is doing with your data.
So when I first looked at Java, I was skeptical. A "virtual machine"? Garbage collection? It felt like giving up control. But the more I dug into systems programming - writing kernels, building compilers, working close to the metal - the more I started to appreciate what the JVM actually is. It's not a toy that hides the machine from you. It's a second machine, engineered with decades of thought about memory safety, concurrency, and portability. The JVM does things at runtime - adaptive optimization, escape analysis, lock elision - that a static C compiler simply cannot do, because it lacks runtime profiling data.
This post is my attempt to write the JVM internals guide I wish I had when I started. It targets Java 17 LTS running on HotSpot (OpenJDK) on Linux.
Let's start from the bottom: what does the JVM look like to the operating system?
2. The JVM as a Process (Linux Process Memory Model)
Before we talk about Java heaps and garbage collectors, we need to talk about something more fundamental: the JVM is just a C++ program. When you run java -jar myapp.jar, the Linux kernel launches a regular userspace process. It gets a PID, a virtual address space, file descriptors, signal handlers - the same things any C or C++ binary gets.
The virtual address space of that process looks like this (simplified, x86-64):
+---------------------------+ High addresses (0x7FFF...)
| Kernel Space | (not accessible to userspace)
+---------------------------+
| Stack | Grows downward. main() thread stack.
| | |
| v |
+---------------------------+
| Memory-Mapped Region | mmap'd files, shared libraries (.so),
| | anonymous mappings (including the Java heap!)
+---------------------------+
| ^ |
| | |
| Process Heap | Grows upward via brk()/sbrk().
| | Used by malloc() for small allocations.
+---------------------------+
| BSS Segment | Uninitialized global/static C++ variables (zeroed)
+---------------------------+
| Data Segment | Initialized global/static C++ variables
+---------------------------+
| Text Segment | Executable machine code (read-only)
+---------------------------+ Low addresses (0x0000...)What each segment contains for the JVM process
This is where many JVM blog posts get confused. Let me be precise:
- Text Segment (Code Segment): The compiled C++ machine code of the JVM itself -
libjvm.so, the interpreter loop, the JIT compiler code, the GC implementation. This is not your Java bytecode and not JIT-compiled Java methods. Those live elsewhere (in the CodeCache, which is mmap'd separately). - Data Segment: The JVM's own initialized global and static C++ variables. Things like default flag values, VM version strings, built-in constant tables.
- BSS Segment: The JVM's uninitialized global/static C++ variables, zero-filled at process startup.
- Process Heap (via
brk/sbrk): Used by the C runtime'smallocfor small internal allocations - JVM bookkeeping structures, small temporary buffers,std::vectorinternals. This is not the Java heap. - Memory-Mapped Region (via
mmap): This is where the big things live:- The Java heap - allocated as a large contiguous anonymous mapping at JVM startup. When you pass
-Xmx4g, the JVM callsmmapto reserve up to 4 GB of contiguous virtual address space. Physical pages are committed on demand. - Metaspace - class metadata, allocated in chunks via
mmap. - CodeCache - JIT-compiled native code, also mmap'd.
- Thread stacks - each Java thread's native stack is a separate mmap'd region.
- Direct ByteBuffers - off-heap memory for NIO.
- Shared libraries -
libjava.so,libzip.so,libnet.so, etc.
- The Java heap - allocated as a large contiguous anonymous mapping at JVM startup. When you pass
Key insight: the Java heap is a subset of the process's virtual memory
+-------------------------------------------------------+
| Total Process Virtual Memory |
| |
| +------------------+ +------------+ +-----------+ |
| | Java Heap | | Metaspace | | CodeCache | |
| | (Eden, Survivor, | | (class | | (JIT code)| |
| | Old Gen) | | metadata) | | | |
| +------------------+ +------------+ +-----------+ |
| |
| +-----------+ +----------------+ +---------------+ |
| | Thread | | Direct | | Internal VM | |
| | Stacks | | ByteBuffers | | Data (GC | |
| | (per | | (NIO off-heap) | | structures, | |
| | thread) | | | | symbol tbl) | |
| +-----------+ +----------------+ +---------------+ |
| |
| + JVM C++ code (text) + C++ globals (data/BSS) + ... |
+-------------------------------------------------------+This is why your Java process can use 2x or 3x the memory you set with -Xmx. The -Xmx flag only controls the Java heap. Everything else - Metaspace, CodeCache, thread stacks, direct memory, GC overhead, JVM internals - adds on top of that. Tools like top and ps show the total process RSS, not the Java heap size. Use jcmd <pid> VM.native_memory summary (with -XX:NativeMemoryTracking=summary) to see the full breakdown.
3. JVM Memory Areas
The following diagram shows the JVM's internal memory layout:
+=====================================================================+
| JVM MEMORY (Java 17 HotSpot) |
+=====================================================================+
| |
| GC-MANAGED (Java Heap) NATIVE MEMORY (off-heap) |
| +--------------------------+ +---------------------------+ |
| | Young Generation | | Metaspace | |
| | +-------+ +----+ +----+| | - Klass structures | |
| | | Eden | | S0 | | S1 || | - Method metadata | |
| | +-------+ +----+ +----+| | - Constant pools | |
| +--------------------------+ | - Annotations | |
| | Old Generation (Tenured) | | - Bytecode arrays | |
| | | +---------------------------+ |
| | Long-lived objects, | | CodeCache (segmented) | |
| | promoted from Young Gen | | - Non-method (stubs) | |
| +--------------------------+ | - Profiled (C1 code) | |
| | String Pool | | - Non-profiled (C2 code) | |
| | (interned strings, | +---------------------------+ |
| | on heap since Java 7) | | Thread Stacks (per thread)| |
| +--------------------------+ +---------------------------+ |
| | Direct Memory (NIO) | |
| +---------------------------+ |
| | Internal VM Data | |
| | - GC structures | |
| | - Symbol tables | |
| | - JNI handles | |
| | - Compiler data | |
| +---------------------------+ |
+=====================================================================+Let's walk through each area in detail.
3.1 Java Heap (GC-Managed, Shared Across All Threads)
The Java heap is where all Java object instances and arrays live. It is managed by the garbage collector and shared across all threads. You control its size with -Xms (initial size) and -Xmx (maximum size).
The heap is divided into generations based on the empirical observation that most objects die young (the "generational hypothesis"):
Young Generation
- Eden Space: Where new objects are allocated. In practice, each thread gets a Thread-Local Allocation Buffer (TLAB) - a small chunk of Eden reserved for that thread. Allocating an object in a TLAB is just a pointer bump (increment a pointer by the object's size), which is almost as fast as stack allocation in C. No locking required because TLABs are thread-local. When a TLAB fills up, the thread requests a new one.
- Survivor Spaces (S0 and S1): Two equally-sized spaces, only one of which is active at a time. When Eden fills up, a Minor GC (young collection) runs. It copies live objects from Eden and the active Survivor space into the other Survivor space, incrementing each object's "age" (a counter in the object header's mark word). Objects that have survived enough Minor GCs (controlled by
-XX:MaxTenuringThreshold, default 15 for most collectors) are promoted to the Old Generation. - Young Generation sizing: controlled by
-Xmn(fixed size) or-XX:NewRatio(ratio of Old to Young, default 2, meaning Old is 2x Young).
Old Generation (Tenured)
Objects that survived multiple young GCs live here. The Old Generation is typically much larger than the Young Generation. When it fills up (or when a promotion would overflow it), a Major GC or Full GC runs, which is significantly more expensive because it must scan a much larger region of memory.
String Pool
Java interns string literals and strings explicitly passed to String.intern() into a hash table called the String Pool. Before Java 7, this pool lived in PermGen (which caused notorious OutOfMemoryError: PermGen space when applications interned too many strings). Since Java 7, the String Pool lives on the regular Java heap, so interned strings are subject to normal garbage collection if no live reference exists.
The size of the underlying hash table is controlled by -XX:StringTableSize (default 65536 in Java 17; should be a prime number for good distribution).
3.2 Metaspace (Native Memory, NOT on the Java Heap)
Metaspace replaced PermGen in Java 8. It stores class metadata - the internal data structures HotSpot needs to represent loaded classes at runtime:
- Klass structures: HotSpot's C++ representation of a Java class. An
InstanceKlassholds the class's vtable, itable, field layout, method array, and pointers to its constant pool, superclass, and implemented interfaces. (Note: it's "Klass" with a K - HotSpot uses this spelling to avoid conflicting with the C++ keywordclass.) - Method metadata:
MethodandConstMethodstructures containing bytecode arrays, exception tables, line number tables, local variable tables, and method signatures. - Runtime constant pools: The per-class constant pool, resolved from the
.classfile's constant pool. Contains symbolic references (class names, method names, field names) that get resolved to direct pointers on first use. - Annotations: Runtime-visible annotation data.
Key differences from PermGen:
| Aspect | PermGen (Java 7 and earlier) | Metaspace (Java 8+) |
|---|---|---|
| Location | Contiguous region of the Java heap | Native memory (mmap'd chunks) |
| Default max size | 64-85 MB (fixed) | Unlimited (bounded by OS) |
| Growth | Fixed at startup, could not grow | Grows dynamically, allocates new chunks as needed |
| Common failure | OutOfMemoryError: PermGen space | OutOfMemoryError: Metaspace (only if -XX:MaxMetaspaceSize is set and hit, or OS is out of memory) |
Metaspace tuning flags:
-XX:MetaspaceSize=N: Sets the initial high-water mark. When Metaspace usage crosses this threshold, a GC is triggered to try to unload classes and reclaim space. After GC, the threshold is adjusted (raised or lowered) based on how much was freed. This is not the initial allocation size - it's the GC trigger point.-XX:MaxMetaspaceSize=N: Hard cap on Metaspace usage. Default is unlimited (uses as much native memory as the OS provides). Set this in production to prevent a classloader leak from eating all system memory.
When is Metaspace freed? Class metadata is freed when the ClassLoader that loaded those classes becomes unreachable and is garbage collected. Individual classes cannot be unloaded independently of their classloader. This is why classloader leaks (common in application servers with hot-redeployment) cause Metaspace to grow without bound - the old classloader is still reachable, so none of its classes can be unloaded.
3.3 CodeCache (Native Memory)
The CodeCache stores native machine code generated at runtime by the JVM:
- JIT-compiled methods: Output from the C1 (client) and C2 (server) compilers. When HotSpot decides a method is "hot" (called frequently or has hot loops), it compiles it from bytecode to optimized native machine code and stores the result in the CodeCache.
- Interpreter stubs (codelets): Small pieces of generated machine code that implement individual bytecode instructions in the template interpreter. HotSpot's interpreter is not a simple
switchstatement - it generates native code stubs for each bytecode at JVM startup. - Adapter stubs: Code that handles transitions between interpreted and compiled frames (i2c and c2i adapters), and between Java and native code (JNI stubs).
Segmented CodeCache (Java 9+)
Starting in Java 9, the CodeCache is divided into three segments (the old single-blob design had fragmentation and sweep-efficiency problems):
| Segment | Contents | Why separate |
|---|---|---|
| Non-method code | VM stubs, adapters, interpreter codelets | Rarely freed, long-lived |
| Profiled code | C1-compiled methods with profiling instrumentation | Short-lived (replaced by C2 code) |
| Non-profiled code | C2 fully-optimized methods, C1 methods without profiling | Long-lived, performance-critical |
This segmentation improves code locality (hot C2 code is not interleaved with cold stubs) and makes sweeping more efficient (the profiled segment churns frequently, the others don't).
Tuning:
-XX:ReservedCodeCacheSize=N: Maximum CodeCache size (default 240 MB in Java 17). If the CodeCache fills up, the JIT compiler stops compiling new methods, and your application silently falls back to interpreted execution - a severe performance cliff. MonitorCodeCacheusage in production.
3.4 Thread Stacks (Native Memory)
Each Java thread maps 1:1 to a native OS thread (a kernel pthread on Linux). Each native thread has its own stack, allocated as a separate mmap'd region.
-Xss(or-XX:ThreadStackSize): Controls the stack size per thread. Default is typically 512 KB to 1 MB depending on the platform. A 500-thread application with 1 MB stacks uses 500 MB of virtual memory just for stacks.- The stack holds JVM frames - one per active method invocation. Each frame contains local variables, the operand stack, and bookkeeping data. (We'll cover frames in detail in section 4.)
StackOverflowErroris thrown when a thread's stack runs out of space, typically from deep or infinite recursion.
3.5 Direct Memory (Native Memory)
Direct memory is off-heap native memory that Java code can allocate explicitly:
ByteBuffer.allocateDirect(int capacity): Allocates a buffer in native memory. Used heavily by NIO for zero-copy I/O - the OS can DMA directly to/from these buffers without copying through the Java heap.sun.misc.Unsafe.allocateMemory(long size): Raw native allocation. Used by some high-performance libraries (Netty, off-heap caches). This API is being gradually replaced by the Foreign Memory Access API (preview in Java 17, finalized later).
Lifecycle: A DirectByteBuffer object lives on the Java heap like any other object. The native memory it points to is freed when the DirectByteBuffer is garbage collected, via a Cleaner callback (internally, sun.misc.Cleaner or java.lang.ref.Cleaner). This means native memory can linger if GC doesn't run soon enough - a common source of native memory "leaks." You can trigger explicit deallocation by calling ((sun.misc.Cleaner) ((DirectBuffer) buf).cleaner()).clean(), but this is internal API.
Tuning:
-XX:MaxDirectMemorySize=N: Hard cap on direct memory. Default is the value of-Xmx. If exceeded,OutOfMemoryError: Direct buffer memoryis thrown.
3.6 Internal VM Data (Native Memory)
Beyond the major categories above, the JVM allocates native memory for many internal data structures:
- GC data structures: For G1 (the default collector since Java 9):
- Remembered Sets (RSets): Per-region data structures tracking references from other regions into this region. Can consume significant memory (5-20% of heap size in some workloads).
- Card Table: A byte array where each byte covers 512 bytes of heap. Used to track which heap regions contain cross-generational pointers.
- Collection Set: The set of regions selected for the next GC pause.
- Concurrent marking bitmaps: Two bitmaps (previous and next) used by the concurrent marking phase.
- Symbol Table: Interned symbols (class names, method names, field descriptors). Similar to the String Pool but for VM-internal identifiers.
- JNI Handles: Global and local references held by native code via JNI.
- Compiler data: Intermediate representations, profiling data (method invocation counters, branch taken/not-taken counters, type profiles) used by tiered compilation.
- Safepoint state: Data structures for coordinating safepoints (more on this in section 5).
4. Java Threads
4.1 Threading Model
In HotSpot Java 17, every java.lang.Thread maps to exactly one native OS thread (1:1 mapping). When you call new Thread().start(), the JVM calls pthread_create on Linux to create a kernel-scheduled thread.
Note on Virtual Threads: Java 21 (Project Loom) introduced virtual threads with M:N mapping - millions of lightweight virtual threads multiplexed onto a small pool of OS "carrier" threads. Java 17 does not have virtual threads. Everything in this post assumes the 1:1 model.
4.2 Thread Lifecycle (Inside the JVM)
When Thread.start() is called, the JVM does the following:
- Allocate JVM-internal structures: A
JavaThreadC++ object (HotSpot's internal representation), anOSThreadobject, a TLAB (thread-local allocation buffer in Eden), synchronization structures (the thread's parker forLockSupport, a condition variable forObject.wait()). - Allocate a native stack: Via
mmap, sized according to-Xss. - Create the native OS thread:
pthread_createwith the JVM's thread entry-point function as the start routine. - Initialize and run: The new thread initializes its state, transitions from
_thread_newto_thread_in_Java, and calls therun()method of theThread(or theRunnablepassed to it). - Terminate: When
run()returns (or an uncaught exception propagates out), the thread:- Checks if it is the last non-daemon thread. If so, initiates JVM shutdown.
- Removes itself from the thread list.
- Releases its TLAB back to Eden.
- Frees the
OSThreadand signals any threads waiting inThread.join(). - The native thread exits via
pthread_exit.
4.3 Per-Thread Components
Each thread has its own private set of runtime data areas. These are not shared between threads (no synchronization needed to access them):
Program Counter (PC Register)
A pointer to the current bytecode instruction being executed by this thread. If the thread is executing a Java method, the PC points into the method's bytecode array in Metaspace. If the thread is executing a native method (via JNI), the PC is undefined - the native code uses the hardware instruction pointer directly, and the JVM does not track it.
The PC is used by the interpreter to know which instruction to execute next. When a method is JIT-compiled, the PC concept is replaced by the hardware instruction pointer running native code directly.
JVM Stack
Each thread has a private JVM stack. It is a stack of frames, one frame per active method invocation, following LIFO (last-in, first-out) order. When a method is called, a new frame is pushed. When it returns, the frame is popped.
Each frame contains:
1. Local Variable Array
A zero-indexed array of slots. Each slot is the size of a machine word (32 bits logically, 64 bits on modern JVMs). The layout is:
- Slot 0: For instance methods, this is
this(a reference to the receiver object). For static methods, slot 0 is the first parameter. - Slots 1..N: Method parameters, in order.
- Slots N+1..M: Local variables declared in the method body.
Type-to-slot mapping:
| Type | Slots consumed |
|---|---|
boolean, byte, char, short, int, float | 1 |
long, double | 2 (consecutive slots) |
| Object reference | 1 |
Example: for the method void foo(int a, long b, String s) in an instance class:
Slot 0: this (reference, 1 slot)
Slot 1: a (int, 1 slot)
Slot 2-3: b (long, 2 slots)
Slot 4: s (reference, 1 slot)2. Operand Stack
The JVM is a stack-based virtual machine, not register-based (unlike, say, the Dalvik/ART VM on Android or Lua's VM). Bytecode instructions operate by pushing values onto and popping values from the operand stack.
Example - compiling int x = 42;:
int x = 42;Bytecode:
bipush 42 // Push the byte-sized constant 42 onto the operand stack
istore_1 // Pop the top of the operand stack and store it in local variable slot 1Step by step:
After bipush 42:
Operand Stack: [ 42 ] <- top
Local Vars: [ this | ? ]
After istore_1:
Operand Stack: [ ] <- empty
Local Vars: [ this | 42 ]A more involved example - int z = x + y; (assuming x is in slot 1, y in slot 2, z goes in slot 3):
iload_1 // Push local var slot 1 (x) onto operand stack
iload_2 // Push local var slot 2 (y) onto operand stack
iadd // Pop two ints, add them, push result
istore_3 // Pop result, store in local var slot 3 (z)Important: A bare declaration like
int i;with no assignment produces no bytecode at all. The local variable slot exists in the frame, but no instruction writes to it until you assign a value. The Java compiler will refuse to let you readibefore assignment (definite assignment analysis), so the absence of initialization bytecode is safe.
3. Dynamic Linking (Runtime Constant Pool Reference)
Each frame holds a reference to the runtime constant pool of the class that owns the current method. The constant pool contains symbolic references - class names like "java/lang/String", method names like "println", field names like "out".
On first use, these symbolic references are resolved to direct pointers:
- A class reference becomes a pointer to the
Klassstructure in Metaspace. - A method reference becomes a pointer to the
Methodstructure (or a vtable/itable index for virtual dispatch). - A field reference becomes a byte offset from the object's base address.
This resolution is lazy by default - it happens the first time the bytecode instruction that references that constant pool entry is executed. Once resolved, the direct pointer is cached in the constant pool so subsequent accesses are fast. This is what "dynamic linking" means in JVM context - linking (symbol resolution) happens at runtime, not at compile time.
4. Return Address
When a method is invoked, the frame stores where execution should resume in the caller after this method returns. For interpreted code, this is the bytecode index of the instruction following the invoke* instruction. For compiled code, this is a native return address (managed by the hardware call stack conventions).
If the method exits via an exception that is not caught within the method, the return address is not used. Instead, the JVM consults the method's exception table to find a matching handler, and if none is found, pops the frame and repeats the process in the caller.
Native Method Stack
When a thread calls a native method (declared with the native keyword, implemented in C/C++ via JNI), execution transitions from the JVM stack to a separate native method stack. This is a standard C-style call stack. The JVM creates a "JNI frame" on the JVM stack as a placeholder, but the actual native execution uses the native stack.
Each thread has its own native method stack. Its size is controlled by the same -Xss flag (on most platforms, the JVM stack and native stack share the same OS thread stack).
Errors
StackOverflowError: Thrown when a method invocation would exceed the thread's stack size. Most commonly caused by infinite recursion or very deep recursion. The JVM reserves a small "shadow zone" at the bottom of each stack so there is enough space to construct and throw the error itself.OutOfMemoryError: Thrown when the JVM cannot allocate a new thread stack (the OS is out of virtual memory or the process has hit its thread limit, e.g.,ulimit -uon Linux).
5. JVM System Threads
When you start a Java application, jstack or Thread.getAllStackTraces() will show you the application threads you created. But the JVM also creates several system threads that run in the background, invisible to your Java code. These are critical to how the JVM operates:
VM Thread
The VM Thread is a special singleton thread that executes VM Operations - tasks that require the entire JVM to be in a consistent state. These operations run at safepoints.
A safepoint is a point in execution where all Java threads are guaranteed to be in a known, consistent state - not in the middle of modifying an object header, not halfway through a pointer update, not between loading a reference and using it. The JVM needs this guarantee for operations that must see a coherent view of the heap.
How safepoints work:
- The VM Thread requests a safepoint.
- All Java threads are asked to pause. Interpreted threads check a safepoint flag at backward branches and method entries. JIT-compiled code has safepoint polls inserted by the compiler at strategic points (loop back-edges, method returns). Threads blocked in native code are "safe" by definition (they can't touch Java heap objects without going through JNI, which checks the safepoint flag).
- Once all threads have reached a safepoint, the VM Thread executes the operation.
- All threads are resumed.
Common VM Operations that require safepoints:
- Stop-the-world GC phases: The initial mark and final remark phases of G1, or a Full GC.
- Thread dump (
jstack,kill -3): Must see all threads' stacks at a consistent point. - Deoptimization: When a JIT-compiled method's assumptions are invalidated (e.g., a class is loaded that changes the class hierarchy), the compiled code must be replaced with interpreted execution.
- Class redefinition (JVMTI, used by debuggers and profilers).
- Biased lock revocation: (Note: biased locking was deprecated in Java 15 and removed in Java 18. In Java 17 it is disabled by default but still present in the codebase. When enabled, revoking a biased lock requires a safepoint.)
GC Threads
The garbage collector uses dedicated threads. G1, the default collector since Java 9, uses two types:
- Concurrent marking threads: Run concurrently with application threads during G1's concurrent marking phase. They trace the object graph to determine which objects are live, without stopping the application (mostly - there are brief STW pauses for initial mark and remark).
- Parallel GC threads: Run during STW pauses (young collection, mixed collection, full GC). Multiple threads work in parallel to evacuate live objects from collected regions to survivor/old regions.
The number of parallel GC threads is controlled by -XX:ParallelGCThreads (defaults to the number of CPU cores, capped at 8 + 5/8 of cores beyond 8). Concurrent threads are controlled by -XX:ConcGCThreads (defaults to ~1/4 of ParallelGCThreads).
Compiler Threads
HotSpot uses tiered compilation by default, employing two JIT compilers:
- C1 (Client Compiler): Fast compilation, moderate optimization. Produces code quickly so methods don't stay interpreted for long. C1-compiled code includes profiling instrumentation - invocation counters, branch statistics, type profiles - that feeds into C2's optimization decisions.
- C2 (Server Compiler): Slow compilation, aggressive optimization. Applies techniques like escape analysis (to eliminate unnecessary heap allocations), loop unrolling, vectorization (auto-SIMD), null-check elimination, range-check elimination, inlining, and dead code elimination. Produces the highest-quality native code.
The tiered compilation pipeline:
Level 0: Interpreter (with basic profiling: invocation counter)
|
v
Level 1-3: C1 compiled (with increasing levels of profiling)
|
v
Level 4: C2 compiled (fully optimized, no profiling overhead)The number of compiler threads is controlled by -XX:CICompilerCount (default depends on CPU cores). Roughly 1/3 are C1 threads and 2/3 are C2 threads.
Periodic Task Thread
A single thread that fires at regular intervals (~50ms by default) to perform housekeeping:
- Sampling: Records which methods are on the stack (used by the JVM's internal profiling for compilation decisions).
- Updating statistics: JVM performance counters, memory usage stats.
- Checking for safepoint requests: Ensures safepoint requests are not missed.
Signal Dispatcher Thread
A dedicated thread that receives OS signals and dispatches them to the appropriate JVM handlers:
SIGINT(Ctrl+C): Initiates JVM shutdown (runs shutdown hooks).SIGTERM: Same as SIGINT - graceful shutdown.SIGHUP: On some systems, triggers a heap dump or other diagnostic action.SIGQUIT(Ctrl+\, orkill -3): Prints a thread dump to stderr. Does not terminate the JVM - this is one of the most useful debugging tools in production.
The signal dispatcher exists because signal handlers in Unix have severe restrictions on what they can do safely (only async-signal-safe functions). The dispatcher thread receives the signal notification and then executes the full handling logic in a normal thread context.
Service Thread
Handles JVM service-layer tasks:
- JMX (Java Management Extensions): Processing MBean requests for monitoring.
- JVMTI (JVM Tool Interface): Dispatching events to attached agents (debuggers, profilers like async-profiler).
- Low-memory notifications: Triggering
MemoryMXBeanlisteners when heap usage crosses thresholds.
6. Shared Memory Areas and Thread Safety
Two JVM memory areas are shared across all threads: the Heap and the Method Area (implemented as Metaspace in Java 17). Sharing requires careful thread safety, and HotSpot uses several mechanisms:
Class Loading is Thread-Safe
When two threads simultaneously trigger loading of the same class (e.g., both hit a new Foo() for a class not yet loaded), the class loading mechanism is synchronized:
- The first thread to attempt loading acquires a per-class-name lock (internally, a hash table mapping class names to
PlaceholderEntryobjects with associated monitors). - The second thread finds the placeholder, sees that loading is in progress, and blocks on the monitor.
- The first thread completes loading (load, link, initialize), stores the resulting
Klassin the system dictionary, and notifies the waiting thread. - The second thread wakes up, finds the
Klassalready loaded, and uses it directly.
This is specified by the JVM specification (JVMS, section 5.3.2) to prevent the same class from being defined twice by the same classloader.
Constant Pool Resolution is Synchronized
When a symbolic reference in a constant pool is resolved for the first time, HotSpot uses compare-and-swap (CAS) operations to atomically update the constant pool entry from the symbolic reference to the resolved direct pointer. If two threads race to resolve the same entry, one wins the CAS and the other sees the already-resolved value. The resolution is idempotent - resolving the same symbol twice yields the same result - so this is safe without heavyweight locking.
Heap Access and the Java Memory Model
Object field reads and writes on the heap are governed by the Java Memory Model (JMM, JSR 133, specified in JLS Chapter 17). The JMM defines when writes by one thread become visible to reads by another thread. Without explicit synchronization (synchronized, volatile, final field semantics, VarHandle acquire/release), there is no guarantee that one thread's writes will be seen by another thread, and the compiler and CPU are free to reorder operations.
This is a deep topic on its own, well beyond the scope of this post - but it's important to understand that "shared memory" does not mean "automatically visible to all threads." Visibility requires synchronization.
This concludes the first half of the post. The second half will cover: the ClassLoader subsystem (Bootstrap, Platform, and Application ClassLoaders in Java 9+, the module system, and delegation), the Execution Engine (interpreter, C1/C2 tiered compilation in depth, and deoptimization), Garbage Collection (G1 in detail, ZGC and Shenandoah), JVM startup and the java launcher, and how to observe all of this in practice with diagnostic tools (jcmd, jhsdb, async-profiler, JFR).
7. Class Loading Subsystem
The class loading subsystem is responsible for finding .class files, reading them into memory, and transforming them into runtime data structures the JVM can use. It has three phases: Loading, Linking, and Initialization. Understanding the boundaries between these phases is critical - many blog posts conflate them, which leads to incorrect mental models.
7.1 Loading
Loading is the act of finding the binary representation of a class (the .class file) and creating an initial internal representation from it.
The Three Built-In ClassLoaders (Java 17)
Java 17 has three built-in classloaders arranged in a parent-child hierarchy:
-
Bootstrap ClassLoader: Implemented in native C++ code inside the JVM itself. It loads the
java.basemodule and other core platform classes that the JVM cannot function without (java.lang.Object,java.lang.String,java.lang.Class,java.lang.Thread, etc.). The Bootstrap ClassLoader has no parent and is not an instance ofjava.lang.ClassLoader- callingString.class.getClassLoader()returnsnull. You cannot replace or extend it from Java code. -
Platform ClassLoader: Loads classes from platform modules that are part of the JDK but not part of
java.base. These includejava.sql,java.xml,java.logging,java.naming,java.desktop, and others. Its parent is the Bootstrap ClassLoader.What changed: In Java 8 and earlier, this role was filled by the Extension ClassLoader, which loaded JAR files from the
jre/lib/extdirectory. Java 9's module system eliminated the extension mechanism entirely. Thelib/extdirectory no longer exists, and the Extension ClassLoader was renamed to the Platform ClassLoader. If you see blog posts referencing the "Extension ClassLoader" orlib/ext, that information is outdated. -
Application ClassLoader (also called the System ClassLoader): Loads classes from the module path (
--module-path) and the classpath (-cp/-classpath). This is the classloader that loads your application code. Its parent is the Platform ClassLoader. You can retrieve it withClassLoader.getSystemClassLoader().
Parent-First Delegation Model
When a classloader is asked to load a class, it does not immediately search its own sources. Instead, it follows the parent-first delegation model:
- Delegate to the parent classloader first.
- The parent delegates to its parent, recursively, all the way up to the Bootstrap ClassLoader.
- If the Bootstrap ClassLoader cannot find the class, control returns to the child.
- Each child tries to load the class itself, working back down the chain.
Request: load "com.myapp.Main"
Application ClassLoader
--> delegates to Platform ClassLoader
--> delegates to Bootstrap ClassLoader
--> Bootstrap: not in java.base or core modules. FAIL.
<-- Platform: not in platform modules. FAIL.
<-- Application: found on classpath. SUCCESS. Load it.This design prevents user code from shadowing core classes. You cannot create a java.lang.String class in your project and have it loaded instead of the real one - the Bootstrap ClassLoader will always find the core String first.
Custom ClassLoaders
You can create custom classloaders by extending java.lang.ClassLoader and overriding the findClass(String name) method (or, for more control, loadClass(String name)). Custom classloaders are Java objects that live on the heap like any other object.
Common uses:
- Web application containers (Tomcat, Jetty): Use child-first delegation (the reverse of the default). Each web application gets its own classloader that searches its own
WEB-INF/classesandWEB-INF/libbefore delegating to the parent. This allows different web apps to use different versions of the same library without conflict. - Plugin systems (OSGi, IDE plugin frameworks): Each plugin gets its own classloader with carefully controlled visibility to other plugins' classes.
- Hot-reloading frameworks (Spring DevTools, JRebel): Create a new classloader to load modified classes, replacing the old classloader. Since classes can only be unloaded when their classloader is GC'd, this effectively "reloads" the class by loading a new version through a new classloader.
What Happens During the Loading Phase
When a classloader loads a class, the JVM performs these steps:
- Find the
.classfile: Search the filesystem, a JAR file, the network, or generate the bytes at runtime (e.g.,java.lang.reflect.Proxygenerates proxy classes dynamically). - Read the bytes into a byte array: The raw binary content of the
.classfile. - Parse the class file format: The JVM verifies and parses the binary structure:
- Magic number: The first 4 bytes must be
0xCAFEBABE(a Java tradition since 1991). - Version numbers: Minor and major version (Java 17 = major version 61). The JVM refuses to load class files with a version newer than it supports.
- Constant pool: A table of constants - string literals, class names, method names, field descriptors, numeric constants, method handles, invoke-dynamic call site specifiers.
- Access flags: Whether the class is
public,final,abstract, an interface, an enum, a module, etc. this_classandsuper_class: Constant pool indices identifying this class and its superclass.- Interfaces: Constant pool indices for all implemented interfaces.
- Fields: Each field's name, descriptor (type signature), and access flags.
- Methods: Each method's name, descriptor, access flags, and attributes (including the
Codeattribute containing the actual bytecode). - Attributes: Class-level attributes like
SourceFile,InnerClasses,BootstrapMethods, annotations, etc.
- Magic number: The first 4 bytes must be
- Recursively load the superclass and interfaces: Before a class can be fully loaded, its superclass and all implemented interfaces must be loaded first (all the way up to
java.lang.Object). - Create a
java.lang.Classobject on the heap: This is the "mirror" object - the Java-visible representation of the class. When you writeMyClass.classor callobj.getClass(), you get this object. It lives on the regular Java heap and is subject to garbage collection (though it won't be collected while its classloader is reachable). - Store class metadata (Klass structure) in Metaspace: The JVM creates an
InstanceKlass(orArrayKlassfor array types) in Metaspace. This C++ structure holds the vtable, itable, field layout, method pointers, constant pool, and other metadata. Thejava.lang.Classmirror on the heap and theKlassin Metaspace point to each other.
7.2 Linking
Linking takes the raw loaded class and transforms it into a state the JVM can execute. It has three sub-phases: Verification, Preparation, and Resolution. These are peers, not nested - they happen as distinct steps.
1. Verification
The JVM verifier checks that the loaded bytecode is structurally correct and type-safe. This is a security-critical step - it prevents malicious or corrupted class files from crashing the JVM or violating memory safety. Verification happens in four passes:
- Pass 1 - File format verification: Confirms the magic number, version, constant pool structure, and that the file is well-formed. This happens during Loading, before the bytes are even turned into internal structures.
- Pass 2 - Metadata verification: Checks class-level constraints. Does the superclass exist and is it not
final? Does the class properly implement all interface methods it claims to? Are there illegal field/method combinations (e.g., a method that is bothabstractandfinal)? - Pass 3 - Bytecode verification: The most complex pass. For each method, the verifier performs abstract interpretation of the bytecode, using stack map frames (mandatory since Java 7 class files, class version 51.0) to verify type safety at each point in the code. It checks:
- The operand stack never overflows or underflows.
- Local variables are not read before being assigned.
- All type casts are to valid types.
- Method invocations have the correct argument types and counts.
- Field accesses use the correct field types.
- Jump targets are within the method's code and land on valid instruction boundaries.
- Pass 4 - Symbolic reference verification: Checks that symbolic references in the constant pool refer to classes, methods, and fields that actually exist and are accessible. This pass can be deferred until Resolution.
You can skip verification with -Xverify:none or -noverify (deprecated in Java 13, likely removed in a future version). Never do this in production - it removes a critical safety net.
2. Preparation
The JVM allocates memory for the class's static fields and initializes them to their type-default values:
| Type | Default Value |
|---|---|
int, short, byte, char | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
boolean | false |
| Object reference | null |
This is not the programmer's assigned value. If you write static int MAX = 100;, after Preparation, MAX is 0. The assignment to 100 happens later, during Initialization.
Preparation also creates method dispatch tables:
- vtable (virtual method table): Used for virtual method dispatch. Contains one entry per virtual method, pointing to the most specific implementation. Inherited methods from superclasses are included.
- itable (interface method table): Used for interface method dispatch. Maps interface methods to their concrete implementations.
3. Resolution
Resolution converts symbolic references in the constant pool to direct references (actual memory addresses or offsets). A symbolic reference is a textual name like "java/io/PrintStream.println:(Ljava/lang/String;)V". A direct reference is a pointer to the Method structure in Metaspace, or a vtable/itable index.
Resolution can be eager (resolve everything at link time) or lazy (resolve on first use). HotSpot uses lazy resolution by default - a symbolic reference is resolved the first time a bytecode instruction references it.
Types of references that get resolved:
- Class and interface references: Symbolic name to
Klass*pointer. - Field references: Symbolic name to a byte offset from the object's base address (for instance fields) or a pointer to the static field storage (for static fields).
- Method references: Symbolic name to a
Method*pointer or a vtable/itable index. - Interface method references: Similar to method references but resolved through the itable.
- Method handles and call site specifiers: Used by
invokedynamic(lambdas, string concatenation in Java 9+).
If resolution fails (e.g., a class is missing, a method doesn't exist, access is denied), the JVM throws an error such as NoClassDefFoundError, NoSuchMethodError, NoSuchFieldError, or IllegalAccessError. These errors are thrown at the point of first use if resolution is lazy.
7.3 Initialization
Initialization is where the class "comes alive." This is when static blocks run and static fields receive their programmer-assigned values.
The Java compiler (javac) generates a special synthetic method called <clinit> (class initializer) for any class that has static field initializers or static {} blocks. This method combines all static field assignments and static blocks in source order into a single method.
Example:
public class Config {
static int MAX = 100; // (1) assigned in <clinit>
static List<String> ITEMS; // (2) default null from Preparation
static { // (3) static block
ITEMS = new ArrayList<>();
ITEMS.add("default");
}
static int MIN = -1; // (4) assigned in <clinit>
}The compiler generates one <clinit> method that executes in this order:
- Set
MAX = 100(from declaration at line 1) - Create a new
ArrayList, assign it toITEMS(from the static block) - Call
ITEMS.add("default")(from the static block) - Set
MIN = -1(from declaration at line 4)
Note that after Preparation, MAX is 0, ITEMS is null, and MIN is 0. Only after Initialization runs do they have their intended values.
Thread Safety of Initialization
Initialization is guaranteed to run exactly once, even when multiple threads trigger it concurrently. The JVM uses an internal initialization lock per class (not the class's java.lang.Class monitor, but a separate VM-internal lock). The protocol works like this:
- Thread A triggers initialization of class
C. It acquiresC's initialization lock and setsC's state to "being initialized by Thread A." - Thread B also triggers initialization of class
C. It sees "being initialized by Thread A" and blocks on the initialization lock. - Thread A finishes running
<clinit>. It setsC's state to "fully initialized" and releases the lock, notifying all waiting threads. - Thread B wakes up, sees "fully initialized," and proceeds without running
<clinit>again.
If Thread A's <clinit> throws an exception, the class is marked as "erroneous." Thread B (and all future attempts to use the class) will receive a NoClassDefFoundError, wrapping the original exception as the cause.
Deadlock warning: If class A's <clinit> triggers initialization of class B, and class B's <clinit> triggers initialization of class A (on a different thread), you get a classloader deadlock. This is a real production issue that is extremely difficult to diagnose.
When Does Initialization Happen?
The JVM specification (JVMS 5.5) defines "active use" as the trigger. A class is initialized on its first active use:
- Creating a new instance (
new). - Accessing a static field (reading or writing) - except
static finalfields with compile-time constant values (see below). - Calling a static method.
- Using reflection (
Class.forName(), unlessinitialize=false). - Initializing a subclass (the superclass is initialized first).
- Being the main class (the class containing
main()that the JVM was invoked with). - A
MethodHandleorVarHandleresolution that implies the class must be initialized.
Important exception: static final fields initialized with compile-time constant expressions (primitive values or String literals known at compile time) are inlined by javac at every call site. Accessing such a field does not trigger class initialization, because the call site already has the constant baked in.
class Constants {
static final int TIMEOUT = 30; // compile-time constant, inlined
static final String NAME = "app"; // compile-time constant, inlined
static final int COMPUTED = Runtime.getRuntime().availableProcessors();
// NOT a compile-time constant
static { System.out.println("Initialized!"); }
}
// Accessing TIMEOUT or NAME does NOT print "Initialized!"
// Accessing COMPUTED DOES print "Initialized!"7.4 Unloading
Classes can be unloaded from the JVM under specific conditions. All of the following must be true:
- The ClassLoader that loaded the class is unreachable (eligible for garbage collection).
- There are no live instances of the class on the heap.
- There are no live references to the class's
java.lang.Classobject.
When a classloader is garbage collected, all classes it loaded are unloaded together. Individual classes cannot be unloaded independently of their classloader.
Key constraints:
- Classes loaded by the Bootstrap ClassLoader are never unloaded. The Bootstrap ClassLoader is always reachable (it is part of the JVM itself).
- Classes loaded by the Platform and Application ClassLoaders are theoretically unloadable, but in practice these classloaders are almost always reachable throughout the JVM's lifetime.
- In practice, class unloading primarily affects classes loaded by custom classloaders - web application classloaders in servlet containers, plugin classloaders, dynamic code generation frameworks.
When classes are unloaded, their Metaspace memory is reclaimed. This is controlled by the flag -XX:+ClassUnloading (on by default). Disabling it with -XX:-ClassUnloading prevents the GC from unloading classes, which can cause Metaspace to grow without bound in applications that create and discard classloaders.
7.5 Worked Example: Tracing Class Loading Through All Phases
Let's trace exactly what happens with two classes, A and Main:
public class A {
static int counter;
static final String TAG = "hello"; // compile-time constant
static {
counter = 42;
System.out.println("A initialized, counter=" + counter);
}
int value;
public A(int v) {
this.value = v;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(A.TAG); // Does NOT trigger A's initialization
A obj = new A(10); // Triggers A's initialization
System.out.println(obj.value);
}
}Step 1 - Loading Main:
- The JVM launcher asks the Application ClassLoader to load
Main. - Application delegates to Platform, Platform delegates to Bootstrap.
- Bootstrap does not have
Main. Platform does not haveMain. - Application finds
Main.classon the classpath, reads the bytes, parses the class file. Main's superclass (java.lang.Object) is already loaded by Bootstrap.- A
java.lang.Classmirror forMainis created on the heap. - An
InstanceKlassforMainis created in Metaspace.
Step 2 - Linking Main:
- Verify: Bytecode is checked for structural correctness and type safety.
- Prepare:
Mainhas no static fields, so nothing to prepare. Method tables are built. - Resolve: Lazy. Symbolic references in Main's constant pool (
A.TAG,A.<init>,System.out,PrintStream.println, etc.) remain as symbolic strings.
Step 3 - Initialization Main:
Mainhas nostatic {}block and no static field initializers. There is no<clinit>method. Initialization is trivially complete.
Step 4 - Executing main():
System.out.println(A.TAG): The compiler inlinedA.TAGas the literal string"hello"at compile time. The bytecode here isldc "hello"followed byinvokevirtual PrintStream.println. ClassAis not loaded or initialized by this line. The output ishello.A obj = new A(10): The bytecode isnew A/dup/bipush 10/invokespecial A.<init>. Thenewinstruction triggers:- Resolution of the symbolic reference
AinMain's constant pool. This triggers Loading of classA. Ais loaded: bytes read, class file parsed, superclass verified (already loaded),java.lang.Classmirror created,InstanceKlasscreated in Metaspace.- Linking of
A:- Verify: A's bytecode is verified.
- Prepare:
counteris allocated and set to default value0.TAGis astatic finalcompile-time constant, so it may be handled specially (its value is in the constant pool). - Resolve: Lazy - symbolic references in A's constant pool are not resolved yet.
- Initialization of
A:<clinit>runs:- Sets
counter = 42. - Calls
System.out.println("A initialized, counter=42"). - Output:
A initialized, counter=42
- Sets
- Now that
Ais fully initialized, thenewinstruction allocates memory for anAinstance in the current thread's TLAB (in Eden). invokespecial A.<init>runs the constructor: setsthis.value = 10.
- Resolution of the symbolic reference
System.out.println(obj.value): Readsobj.value(which is10) and prints it. Output:10.
Complete output:
hello
A initialized, counter=42
10Notice the key insight: A.TAG did not cause A to be initialized because TAG is a compile-time constant that was inlined by javac. The new A(10) line is what actually triggered loading, linking, and initialization of A.
8. The Execution Engine
The execution engine is the component that actually runs your bytecode. HotSpot uses a mixed-mode strategy: start with interpretation, then selectively compile hot methods to native code. This gives you fast startup (no compilation delay) and peak throughput (hot paths run as native machine code).
8.1 The Template Interpreter
HotSpot does not use a naive switch-case interpreter loop. Instead, it uses a template interpreter: at JVM startup, the interpreter generates a small block of native machine code (a "template" or "codelet") for each bytecode instruction. At runtime, interpreting bytecode is a matter of jumping between these pre-generated templates.
For example, the iadd bytecode (integer add) has a template that:
- Pops two integers from the operand stack (which, in practice, is mapped to a region of the native stack frame).
- Adds them using a native
addinstruction. - Pushes the result.
- Reads the next bytecode opcode.
- Jumps to the next template via an indirect jump (computed goto).
This template-based approach is significantly faster than a switch statement because it avoids the overhead of a dispatch loop - there is no loop variable, no case comparison, just direct jumps between code blocks. The branch predictor on modern CPUs can predict indirect jumps reasonably well, making this approach quite efficient.
However, the interpreter is still much slower than JIT-compiled code because each bytecode is executed independently. There is no cross-instruction optimization, no register allocation across operations, and every value passes through the operand stack.
While executing, the interpreter collects profiling data that feeds the JIT compilers:
- Method invocation counts (how many times each method is called).
- Backedge counts (how many times a loop back-edge is taken - this measures loop "hotness").
- Branch profiles (for each conditional branch, how often each direction is taken).
- Type profiles (for virtual calls, what concrete types are actually observed at each call site).
This profiling data is what makes HotSpot's adaptive optimization possible and is a fundamental advantage over static compilers.
8.2 JIT Compilation (Tiered Compilation)
HotSpot Java 17 uses tiered compilation by default (-XX:+TieredCompilation, on by default). This means methods progress through multiple compilation tiers as they get hotter:
| Tier | Compiler | Profiling | Description |
|---|---|---|---|
| Tier 0 | Interpreter | Basic counters | Method invocation count, backedge count |
| Tier 1 | C1 | None | Simple methods compiled quickly, no profiling instrumentation |
| Tier 2 | C1 | Basic | Invocation + backedge counters in compiled code |
| Tier 3 | C1 | Full | Type profiles, branch profiles, receiver type statistics |
| Tier 4 | C2 | None | Fully optimized native code, no profiling overhead |
The typical progression for a method:
- Tier 0 (Interpreter): The method starts out interpreted. The interpreter counts invocations and backedges.
- Tier 3 (C1 + full profiling): When the invocation count + backedge count exceeds a threshold (around 2,000 for invocations, configurable via
-XX:Tier3InvocationThreshold), the method is queued for C1 compilation with full profiling. C1 compiles quickly - it uses a single-pass linear scan register allocator and applies moderate optimizations (method inlining for small methods, constant folding, null check elimination). The compiled code includes instrumentation to continue collecting type profiles and branch statistics. - Tier 4 (C2 fully optimized): If the C1-compiled method remains hot (the profiling counters in the compiled code keep incrementing), it is queued for C2 compilation. C2 is a much more aggressive optimizing compiler. It builds an intermediate representation called the "Ideal Graph" (a sea-of-nodes SSA IR), applies extensive optimizations, and generates highly tuned native code.
Why Tier 1 and Tier 2 exist: Tier 1 (C1, no profiling) is used for trivially simple methods - getters, setters, methods with no control flow - where profiling would add overhead but there is nothing useful to profile. Tier 2 (C1, basic profiling) is a fallback used when the C1 compilation queue is full and the method needs at least some profiling before being promoted to C2.
Compilation thresholds: You can observe compilations with -XX:+PrintCompilation. The flag -XX:CompileThreshold sets the threshold for compilation in non-tiered mode. In tiered mode, the thresholds per tier are controlled by flags like -XX:Tier3InvocationThreshold, -XX:Tier4InvocationThreshold, etc.
Key C2 Optimizations
C2 applies the optimizations that give Java its competitive performance:
- Inlining: The single most important optimization. C2 replaces method calls with the body of the called method. This eliminates call overhead and, more importantly, exposes the inlined code to further optimizations (constant propagation, dead code elimination, etc.). Inlining is guided by profiling data - if a virtual call site always sees the same concrete type, C2 can inline the specific implementation. Controlled by
-XX:MaxInlineSize(default 35 bytecodes for cold methods),-XX:FreqInlineSize(default 325 for hot methods), and-XX:InlineSmallCode. - Escape Analysis: Determines whether an object "escapes" the method that created it (i.e., is accessible outside that method or thread). If an object does not escape:
- Scalar replacement: The object's fields are replaced with individual local variables, and the allocation is eliminated entirely. The "object" never exists on the heap.
- Stack allocation: In theory, the object could be allocated on the stack. In practice, HotSpot primarily uses scalar replacement rather than true stack allocation.
- Lock elision: If a synchronized block operates on a non-escaping object, the lock is unnecessary and is removed.
- Loop optimizations: Unrolling (repeating the loop body to reduce branch overhead), peeling (extracting the first iteration), hoisting loop-invariant code out of the loop, range check elimination (removing array bounds checks when the compiler can prove they always pass).
- Vectorization (Auto-SIMD): C2 can vectorize certain loop patterns to use SIMD instructions (SSE, AVX on x86-64), processing multiple data elements per instruction. This requires recognizing specific loop patterns over arrays with compatible types.
- Null check elimination: If the compiler can prove that a reference is never null at a given point (e.g., it was just loaded from a non-null field and no intervening code could have changed it), it eliminates the null check.
- Dead code elimination: Code that cannot affect the program's observable behavior is removed.
- Common subexpression elimination: If the same computation appears twice and the inputs haven't changed, compute it once and reuse the result.
8.3 On-Stack Replacement (OSR)
Normal JIT compilation triggers when a method is called often enough. But what about a method that is called once but contains a very long-running loop?
public void process() {
for (int i = 0; i < 10_000_000; i++) {
// heavy computation
}
}This method is called once, so its invocation count is 1 - below the compilation threshold. But the loop body executes 10 million times, and the backedge counter (incremented at each loop iteration) will quickly cross the threshold.
On-Stack Replacement (OSR) handles this case. When the backedge counter exceeds the threshold, the JVM compiles the method (specifically, the version starting from the loop entry point) and replaces the currently executing interpreted frame with the compiled version, mid-execution. The thread transitions from interpreted mode to compiled mode without leaving the method and without restarting from the beginning.
OSR is more complex than regular JIT compilation because the compiled code must accept the current state of local variables and the operand stack from the interpreter frame.
8.4 Deoptimization
C2 makes speculative optimizations based on profiling data. If the speculation turns out to be wrong, the JVM must deoptimize: discard the compiled code and fall back to the interpreter.
Common deoptimization triggers:
- Class loading invalidates a type assumption: C2 might inline a virtual call assuming the call site is monomorphic (only one concrete type was ever observed). If a new class is loaded that makes the call site polymorphic, the inlined code is no longer correct.
- Uncommon trap: C2 marks rarely-taken code paths (based on profiling data) as "uncommon traps." If execution actually reaches one of these paths, the compiled code triggers a deoptimization. The interpreter will then execute the rare path correctly. This lets C2 optimize aggressively for the common case without generating code for rare paths.
- Array bounds check that was eliminated fails: If C2 eliminated an array bounds check based on range analysis, but the range assumption is violated at runtime, deoptimization occurs.
Deoptimization is safe because the interpreter can always execute any valid bytecode. The process works like this:
- Execution hits a deoptimization trigger in compiled code.
- The JVM constructs an equivalent interpreter frame from the compiled frame's state (local variables, expression stack values).
- The compiled frame is replaced with the interpreter frame on the thread's stack.
- Execution continues in the interpreter.
- The compiled code is typically marked for recompilation (with updated profiling data).
You can observe deoptimizations with -XX:+TraceDeoptimization (diagnostic flag, requires -XX:+UnlockDiagnosticVMOptions).
8.5 GraalVM and Alternatives
While this post focuses on HotSpot's C1 and C2 compilers (which are part of the standard OpenJDK 17 distribution), it is worth knowing about GraalVM:
- Graal JIT compiler: A JIT compiler written in Java (instead of C++) that can be used as a drop-in replacement for C2. It offers some optimizations that C2 does not, particularly around partial escape analysis. The Graal JIT can be used with the JVMS flag
-XX:+UseJVMCICompilerwhen running on GraalVM or with the Graal module on the module path. - Native Image: GraalVM's
native-imagetool performs ahead-of-time (AOT) compilation to produce standalone native binaries. This eliminates startup time and reduces memory footprint but sacrifices peak throughput (no profile-guided optimization at runtime) and requires a closed-world assumption (all code must be known at build time).
Neither of these is part of standard OpenJDK 17, but they are increasingly relevant in the Java ecosystem, especially for cloud-native and serverless deployments where startup time matters.
9. Garbage Collection in Java 17
Garbage collection is the JVM's automatic memory management system. Instead of manual malloc/free (as in C), or reference counting (as in Python/Swift), the JVM uses tracing garbage collection: it periodically traces all reachable objects starting from a set of "roots" (local variables, static fields, JNI references) and reclaims everything that is not reachable.
9.1 The Generational Hypothesis
Empirical studies of object lifetimes across many programs show a consistent pattern: most objects die young. An object allocated in a tight loop typically becomes garbage within microseconds. Objects that survive for a while tend to survive for a long time (cached data, configuration, connection pools).
This observation, called the generational hypothesis, is the foundation of generational garbage collection:
- Young Generation: Collect it frequently. Most objects are dead, so the collector mostly copies the few survivors. This is fast.
- Old Generation: Collect it infrequently. Objects here are likely to be long-lived, so there is less garbage to reclaim per collection. These collections are more expensive because the region is larger.
The payoff is significant: a young-generation collection typically takes a few milliseconds and reclaims 90-95% of the objects. Without generational collection, every GC cycle would have to scan the entire heap.
9.2 TLAB (Thread-Local Allocation Buffers)
Before diving into collectors, it is important to understand how objects are allocated, because allocation speed directly affects application performance.
Each thread gets a Thread-Local Allocation Buffer (TLAB) - a small, private chunk of Eden space reserved exclusively for that thread. Allocating an object within a TLAB is a bump-pointer allocation: the thread increments a pointer by the object's size and returns the old pointer value. No locking, no synchronization, no CAS operation.
TLAB for Thread-1:
[allocated objects...][next free --> ][end]
^ ^
allocation pointer TLAB boundaryTo allocate a 32-byte object:
- Check:
allocationPointer + 32 <= end? Yes. - Return
allocationPointeras the new object's address. - Set
allocationPointer += 32.
That is roughly 10 CPU instructions for a new operation. This is comparable in speed to alloca (stack allocation) in C. It is one of the reasons Java object allocation is not the performance problem many C programmers assume it is.
When a TLAB fills up, the thread requests a new one from Eden. This requires synchronization (a CAS on the shared Eden allocation pointer), but it happens infrequently - TLABs are typically sized to hold many allocations between refills.
Objects too large for a TLAB (typically > 50% of the TLAB size) are allocated directly in Eden using a shared allocation pointer with CAS, or (for very large objects) directly in the Old Generation.
9.3 G1 GC (Default Since Java 9)
The Garbage-First (G1) collector is the default collector in Java 9 through Java 17. Its primary design goal is predictable pause times: it aims to keep stop-the-world pauses under a configurable target while providing good throughput.
Region-Based Heap Layout
Unlike traditional collectors that divide the heap into a few large contiguous spaces, G1 divides the entire heap into regions of equal size. The region size is chosen at startup (between 1 MB and 32 MB, always a power of 2) based on the heap size (target: roughly 2048 regions).
Each region is dynamically assigned one of several roles:
+-------+-------+-------+-------+-------+-------+-------+-------+
| Eden | Eden | Surv | Old | Old | Humong| Humong| Free |
| | | | | | ous | ous | |
+-------+-------+-------+-------+-------+-------+-------+-------+
| Free | Old | Eden | Free | Free | Old | Old | Surv |
| | | | | | | | |
+-------+-------+-------+-------+-------+-------+-------+-------+- Eden regions: Where new objects are allocated (via TLABs).
- Survivor regions: Where objects that survive a young GC are copied.
- Old regions: Where objects promoted from Survivor (or directly allocated, if large enough) reside.
- Humongous regions: Objects larger than half a region size. They span one or more contiguous regions and are allocated directly. Humongous objects are collected differently - they can be reclaimed during young GCs if unreachable.
- Free regions: Unassigned, available for any role.
This region-based approach is what gives G1 its flexibility. The collector can choose exactly which regions to collect, balancing the work done against the pause time target.
Young GC (Evacuation Pause)
When Eden fills up (all Eden regions are full), G1 triggers a young garbage collection:
- Stop the world: All application threads are paused at a safepoint.
- Root scanning: Identify objects directly reachable from GC roots (thread stacks, static fields, JNI references).
- Scan remembered sets: Check the remembered sets of collected regions to find references from Old regions into young regions.
- Copy live objects: Live objects in Eden and Survivor regions are copied to new Survivor regions (or promoted to Old regions if they have survived enough collections). This is done in parallel by multiple GC threads.
- Reclaim old regions: The entire Eden and old Survivor regions are freed (they contained only dead objects and the survivors have been copied out).
- Resume application threads.
Young GCs are parallel (multiple GC threads work simultaneously) and always stop-the-world (application threads are paused). Typical young GC pauses are 5-50 ms depending on the heap size and number of surviving objects.
Concurrent Marking
To collect old regions efficiently, G1 needs to know which objects in old regions are live. It discovers this through concurrent marking, which runs mostly concurrently with application threads:
- Initial Mark (STW, piggybacked on a young GC): Mark objects directly reachable from roots.
- Concurrent Mark: Trace the object graph from the initial marks, running concurrently with the application. Uses a SATB (Snapshot-At-The-Beginning) algorithm to handle concurrent mutations.
- Remark (STW): Process remaining SATB buffers, finish marking. Short pause.
- Cleanup (partially STW): Identify completely empty old regions (all objects are dead) and free them immediately. Calculate per-region liveness data. Update remembered sets.
Mixed GC
After concurrent marking completes, G1 has liveness information for all old regions. It then performs mixed collections: young GC pauses that also include some old regions with the most garbage. The name "Garbage-First" comes from this behavior - it collects the regions with the most garbage first, maximizing reclamation per unit of pause time.
The number of old regions included in each mixed GC is tuned to keep the pause within the -XX:MaxGCPauseMillis target (default: 200 ms).
Full GC (Fallback)
If G1 cannot keep up - if the application allocates faster than the collector can free memory - it falls back to a Full GC: a single-threaded (in older versions) or multi-threaded (Java 10+) stop-the-world compacting collection of the entire heap. Full GCs are expensive and indicate that G1 is not configured properly for the workload (heap too small, allocation rate too high, or too many humongous allocations).
9.4 Other Collectors Available in Java 17
Java 17 includes several other garbage collectors for different use cases:
| Collector | Flag | Best For | Pause Behavior |
|---|---|---|---|
| Serial GC | -XX:+UseSerialGC | Small heaps (< 100 MB), single-core machines, containers with limited CPU | Single-threaded STW for all phases |
| Parallel GC | -XX:+UseParallelGC | Throughput-oriented batch processing, large heaps where max throughput matters more than latency | Multi-threaded STW, no concurrent phases |
| ZGC | -XX:+UseZGC | Ultra-low latency requirements (sub-millisecond pauses), large heaps (multi-terabyte capable) | Concurrent; STW pauses are typically < 1 ms regardless of heap size |
| Shenandoah | -XX:+UseShenandoahGC | Similar to ZGC - low-latency concurrent collection. Available in OpenJDK builds (Red Hat, Amazon Corretto, etc.) but not in Oracle's JDK builds | Concurrent; low and predictable pauses |
| Epsilon | -XX:+UseEpsilonGC | Performance testing, memory pressure testing, very short-lived applications that will exit before the heap fills | No-op: never collects. The JVM crashes with OutOfMemoryError when the heap is exhausted |
ZGC deserves special mention. It uses colored pointers (metadata stored in unused bits of 64-bit object references) and load barriers (a small code stub executed on every object reference load) to perform almost all GC work concurrently with the application. In Java 17, ZGC's pause times are typically under 1 millisecond, regardless of heap size - even on heaps of hundreds of gigabytes. The tradeoff is slightly reduced throughput compared to G1 or Parallel GC due to the load barrier overhead.
Note: CMS (Concurrent Mark-Sweep) was deprecated in Java 9 and removed in Java 14. If you see blog posts recommending CMS, that advice is obsolete for Java 17.
10. Putting It All Together: Complete Walkthrough
Let's trace through the complete lifecycle of a Java program, touching every subsystem we have discussed. Here is our example:
public class Counter {
private static int instanceCount;
static {
instanceCount = 0;
System.out.println("Counter class initialized");
}
private int value;
public Counter(int initial) {
this.value = initial;
instanceCount++;
}
public int increment() {
return ++value;
}
public static int getInstanceCount() {
return instanceCount;
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter(10);
Counter c2 = new Counter(20);
System.out.println(c1.increment()); // 11
System.out.println(Counter.getInstanceCount()); // 2
}
}Phase 1: Loading
Main is loaded first.
The JVM launcher calls ClassLoader.getSystemClassLoader().loadClass("Main"), which triggers the Application ClassLoader:
- Application ClassLoader delegates to Platform ClassLoader.
- Platform delegates to Bootstrap ClassLoader.
- Bootstrap does not find
Maininjava.baseor core modules. Returns. - Platform does not find
Mainin platform modules. Returns. - Application ClassLoader finds
Main.classon the classpath. - The bytes are read. The class file is parsed: magic number
0xCAFEBABE, version 61.0 (Java 17), constant pool, methods (main), fields (none), superclass (java/lang/Object, already loaded). - A
java.lang.Classobject forMainis created on the heap. - An
InstanceKlassforMainis created in Metaspace.
Counter is NOT loaded yet. Class loading is lazy. Counter will be loaded when a bytecode instruction in Main.main() first references it.
Phase 2: Linking Main
- Verify: Main's bytecode is checked for structural correctness. The
mainmethod's bytecode is verified: stack map frames are valid, types are consistent, all branches target valid instruction boundaries. - Prepare:
Mainhas no static fields. Its vtable is built (inheritingjava.lang.Object's methods:toString,equals,hashCode, etc.). - Resolve: Lazy. Symbolic references in Main's constant pool (
Counter,Counter.<init>,System.out,PrintStream.println, etc.) remain as symbolic strings.
Phase 3: Initializing Main
Main has no static {} block and no static field initializers. There is no <clinit> method. Initialization is trivially complete.
Phase 4: Executing main()
The JVM calls Main.main(String[]). Let's walk through the bytecode.
Counter c1 = new Counter(10);
The bytecode for this line:
new #2 // class Counter
dup
bipush 10
invokespecial #3 // Method Counter."<init>":(I)V
astore_1 // store in local variable 1 (c1)new Counter: This is the first reference to Counter in executing code.
-
Resolution: The symbolic reference
Counterin Main's constant pool is resolved. This triggers loading ofCounter. -
Loading Counter: Application ClassLoader delegates up, nobody finds it, Application loads it from the classpath. The class file is parsed. The superclass
java.lang.Objectis already loaded. Ajava.lang.Classmirror is created on the heap. AnInstanceKlassis created in Metaspace. TheInstanceKlassrecords:- Static fields:
instanceCount(int) - Instance fields:
value(int) - Methods:
<init>(int),increment(),getInstanceCount(),<clinit>() - Constant pool with all symbolic references
- Static fields:
-
Linking Counter:
- Verify: Counter's bytecode is verified. The
<init>,increment, andgetInstanceCountmethods are all checked. - Prepare: Memory is allocated for the static field
instanceCountand it is set to its default value:0. The vtable is built (inheriting Object's methods, addingincrementas virtual). The itable is empty (Counter implements no interfaces). - Resolve: Lazy. Symbolic references in Counter's constant pool are not resolved yet.
- Verify: Counter's bytecode is verified. The
-
Initialization of Counter: The
newbytecode triggers a class initialization check. Counter has not been initialized yet, so<clinit>runs:// <clinit> bytecode: iconst_0 putstatic #1 // Field instanceCount:I (sets instanceCount = 0) getstatic #2 // Field System.out ldc #3 // String "Counter class initialized" invokevirtual #4 // Method PrintStream.println returninstanceCountis set to0(redundant here since Preparation already set it to0, but this is the programmer's explicit assignment in the static block)."Counter class initialized"is printed to stdout.
Output so far:
Counter class initialized -
Allocation: Now the
newinstruction allocates memory for aCounterinstance. The JVM:- Determines the instance size: object header (mark word + klass pointer = 12 bytes with compressed oops) + one
intfield (value, 4 bytes) = 16 bytes (aligned). - Allocates 16 bytes from the current thread's TLAB in Eden: bump the TLAB's allocation pointer by 16.
- Zeroes the allocated memory.
- Sets the object header: the mark word (initial hash, age=0, no lock) and the klass pointer (pointing to Counter's
InstanceKlassin Metaspace).
- Determines the instance size: object header (mark word + klass pointer = 12 bytes with compressed oops) + one
-
dup: Duplicates the reference on the operand stack (one copy for the constructor call, one for storing in the local variable). -
bipush 10: Pushes the integer10onto the operand stack. -
invokespecial Counter.<init>(int): Calls the constructor. A new frame is pushed onto the JVM stack:Counter.<init>(int) frame: Local Variables: [this=<Counter@addr>, initial=10] Operand Stack: []The constructor bytecode:
aload_0 // push 'this' iload_1 // push 'initial' (10) putfield #1 // this.value = 10 getstatic #2 // push Counter.instanceCount (currently 0) iconst_1 // push 1 iadd // 0 + 1 = 1 putstatic #2 // Counter.instanceCount = 1 returnAfter the constructor:
c1.value = 10,Counter.instanceCount = 1. -
astore_1: Pops the reference from the operand stack and stores it in local variable slot 1 (c1).
Counter c2 = new Counter(20);
Same sequence, but:
Counteris already loaded, linked, and initialized. No class loading happens.- A new 16-byte object is allocated in the thread's TLAB.
- The constructor sets
c2.value = 20and incrementsinstanceCountfrom 1 to 2.
System.out.println(c1.increment());
c1.increment() bytecode:
aload_1 // push c1
invokevirtual #5 // Method Counter.increment:()IThis triggers virtual dispatch. The JVM looks up increment in Counter's vtable and finds the implementation. The increment method's frame:
increment() frame:
Local Variables: [this=c1]
Operand Stack: []Bytecode for increment():
aload_0 // push 'this'
dup // duplicate for putfield and return
getfield #1 // push this.value (10)
iconst_1 // push 1
iadd // 10 + 1 = 11
dup_x1 // duplicate result under 'this'
putfield #1 // this.value = 11
ireturn // return 11The return value 11 is pushed onto the caller's operand stack, then passed to PrintStream.println(int).
Output: 11
System.out.println(Counter.getInstanceCount());
invokestatic #6 // Method Counter.getInstanceCount:()IgetInstanceCount() bytecode:
getstatic #2 // push Counter.instanceCount (2)
ireturn // return 2Output: 2
Phase 5: Garbage Collection
When main() returns:
- The local variables
c1andc2go out of scope. The references are no longer on any thread's stack. - The two
Counterobjects in Eden are now unreachable. - They are not collected immediately. They sit in Eden until the next young GC.
- When a young GC occurs (triggered by Eden filling up from subsequent allocations, or by JVM shutdown), the GC scans roots, finds no references to these objects, and does not copy them to a Survivor region. Their memory is reclaimed by simply freeing the entire Eden region.
Counter.instanceCountis a static field stored in theInstanceKlassin Metaspace. It persists until the class is unloaded (which will not happen for an Application ClassLoader-loaded class under normal circumstances).
Phase 6: JIT Compilation (Hypothetical Hot Loop)
If increment() were called in a hot loop:
for (int i = 0; i < 1_000_000; i++) {
c1.increment();
}The progression would be:
-
Tier 0 (Interpreted): The first ~2,000 iterations of the loop run interpreted. The interpreter collects invocation counts for
increment()and backedge counts for the loop. -
Tier 3 (C1 with profiling):
increment()reaches the C1 compilation threshold. C1 compiles it to native code with profiling instrumentation. The compiled code records thatthisis always of typeCounter(type profile). -
Tier 4 (C2 fully optimized): If
increment()remains hot (it will - we are in a million-iteration loop), C2 compiles it. C2's optimizations:- Inlining:
increment()is small. C2 inlines it into the loop body inmain(), eliminating the method call overhead entirely. - Escape analysis: After inlining, C2 analyzes
c1. If the object does not escape the method (no other thread can access it, it is not stored in a field visible to other code), C2 may apply scalar replacement: replacec1.valuewith a local variable, eliminating the heap read/write on every iteration. - Loop optimization: With
valuenow a local variable, the loop body is just an integer increment. C2 can unroll the loop (execute multiple iterations per loop check), eliminate the range check, and potentially vectorize if the pattern allows.
The final compiled code might look roughly like this (pseudo-assembly):
; After inlining + escape analysis + loop unrolling: mov eax, [c1 + offset_value] ; load value once add eax, 1000000 ; compiler might even strength-reduce the whole loop mov [c1 + offset_value], eax ; store onceIn the most aggressive case, C2 could recognize that the loop simply adds 1,000,000 to
valueand replace the entire loop with a single addition. This is the power of profile-guided JIT compilation: it can make optimizations that a static compiler (likegccorjavac) cannot, because it knows the runtime behavior. - Inlining:
-
OSR: For the loop itself, OSR may kick in. If the loop starts running interpreted and the backedge counter trips mid-loop, the JVM can compile the loop body and switch from the interpreted frame to the compiled frame without restarting the loop.
Complete output of the original program:
Counter class initialized
11
211. Key JVM Flags for Java 17 (Reference Table)
Here is a quick reference of the most important JVM flags for tuning, diagnostics, and debugging in Java 17.
Heap Sizing
| Flag | Default | Description |
|---|---|---|
-Xms<size> | Varies (typically 1/64 of physical memory) | Initial heap size |
-Xmx<size> | Varies (typically 1/4 of physical memory) | Maximum heap size |
-Xmn<size> | Dynamic (G1 manages this automatically) | Young generation size (fixed). Rarely set manually with G1. |
Metaspace
| Flag | Default | Description |
|---|---|---|
-XX:MetaspaceSize=<size> | ~21 MB | GC trigger threshold for Metaspace. When usage crosses this, GC runs to try to unload classes. |
-XX:MaxMetaspaceSize=<size> | Unlimited | Hard cap on Metaspace. Set in production to prevent classloader leaks from eating system memory. |
Thread Stack
| Flag | Default | Description |
|---|---|---|
-Xss<size> | 512 KB - 1 MB (platform-dependent) | Stack size per thread. Increase for deep recursion; decrease for many threads with shallow stacks. |
Garbage Collection
| Flag | Default | Description |
|---|---|---|
-XX:+UseG1GC | On (default since Java 9) | Use the G1 garbage collector |
-XX:MaxGCPauseMillis=<ms> | 200 | G1's pause time target in milliseconds |
-XX:+UseZGC | Off | Use the ZGC low-latency collector |
-XX:+UseParallelGC | Off | Use the throughput-oriented Parallel collector |
-XX:+UseSerialGC | Off | Use the single-threaded Serial collector |
-XX:+UseShenandoahGC | Off | Use the Shenandoah low-latency collector (OpenJDK only) |
-XX:ParallelGCThreads=<n> | Auto (based on CPU cores) | Number of threads for parallel GC phases |
-XX:ConcGCThreads=<n> | Auto (~1/4 of ParallelGCThreads) | Number of threads for concurrent GC phases |
CodeCache
| Flag | Default | Description |
|---|---|---|
-XX:ReservedCodeCacheSize=<size> | 240 MB | Maximum CodeCache size. If exhausted, JIT compilation stops. |
Direct Memory
| Flag | Default | Description |
|---|---|---|
-XX:MaxDirectMemorySize=<size> | Same as -Xmx | Maximum off-heap direct memory (ByteBuffer.allocateDirect) |
JIT Compilation
| Flag | Default | Description |
|---|---|---|
-XX:+TieredCompilation | On | Enable tiered compilation (Interpreter -> C1 -> C2) |
-XX:TieredStopAtLevel=<n> | 4 | Stop compilation at this tier. Set to 1 for C1-only (faster startup, lower peak perf). |
-XX:CICompilerCount=<n> | Auto | Number of compiler threads (shared between C1 and C2) |
Diagnostics and Debugging
| Flag | Default | Description |
|---|---|---|
-XX:+PrintCompilation | Off | Log each method as it is JIT-compiled (method name, tier, size) |
-Xlog:gc* | Off | Unified logging for GC events (replaces old -XX:+PrintGCDetails) |
-Xlog:gc*:file=gc.log | Off | Write GC logs to a file |
-XX:+HeapDumpOnOutOfMemoryError | Off | Write a heap dump (.hprof file) when OutOfMemoryError is thrown |
-XX:HeapDumpPath=<path> | Current directory | Where to write the heap dump |
-XX:NativeMemoryTracking=summary | Off | Track JVM native memory usage. Query with jcmd <pid> VM.native_memory summary. |
-XX:+UnlockDiagnosticVMOptions | Off | Required to use diagnostic flags like -XX:+TraceDeoptimization |
-XX:StartFlightRecording=... | Off | Start JDK Flight Recorder at JVM launch for production-safe profiling |
Practical Starter Configuration
For a typical Java 17 application in production:
java \
-Xms2g -Xmx2g \
-XX:MaxMetaspaceSize=256m \
-XX:+UseG1GC \
-XX:MaxGCPauseMillis=200 \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/var/log/myapp/ \
-Xlog:gc*:file=/var/log/myapp/gc.log:time,level,tags:filecount=5,filesize=50m \
-XX:NativeMemoryTracking=summary \
-jar myapp.jarThis gives you: a fixed 2 GB heap (avoiding resize pauses), a Metaspace cap (safety net against leaks), G1 with a 200 ms pause target, a heap dump on OOM for post-mortem analysis, rotating GC logs, and native memory tracking for diagnostics.
Conclusion
We have covered the JVM from the ground up:
- Process-level view: The JVM is a C++ process with a standard Linux memory layout. The Java heap, Metaspace, CodeCache, and thread stacks are all
mmap'd regions within that process's virtual address space. - Memory areas: The heap (Eden, Survivor, Old), Metaspace (class metadata in native memory), CodeCache (JIT-compiled code), thread stacks (per-thread, holding frames with local variables and operand stacks), and direct memory (off-heap NIO buffers).
- Threads: 1:1 mapping to OS threads in Java 17. Each thread has a private stack, PC register, TLAB, and frame stack. System threads (GC, compiler, VM thread) run alongside application threads.
- Class loading: Three classloaders (Bootstrap, Platform, Application) with parent-first delegation. Loading reads
.classbytes and creates metadata. Linking verifies, prepares (defaults), and resolves (symbolic to direct references). Initialization runs<clinit>exactly once with thread-safe locking. - Execution engine: Template interpreter for fast startup with profiling. Tiered JIT compilation (C1 for quick compilation, C2 for aggressive optimization). On-stack replacement for hot loops. Deoptimization as a safety net when speculative optimizations fail.
- Garbage collection: Generational hypothesis motivates young/old separation. G1 (the default) uses regions, concurrent marking, and mixed collections to target predictable pause times. ZGC and Shenandoah push pauses below 1 ms. TLABs make allocation nearly free.
Looking Ahead: Java 21 and Beyond
Java 21 (the next LTS after 17) brings significant changes to several areas discussed in this post:
- Virtual Threads (Project Loom): Java 21 introduces virtual threads with M:N scheduling - millions of lightweight threads multiplexed onto a small pool of OS carrier threads. This fundamentally changes the threading model described in section 4. The 1:1 thread-to-stack mapping becomes M:N, and the per-thread memory overhead drops from ~1 MB to ~1 KB, enabling highly concurrent applications without thread pools.
- Generational ZGC: Java 21 adds generational collection to ZGC (
-XX:+UseZGC -XX:+ZGenerational), combining ZGC's sub-millisecond pauses with the efficiency gains of generational collection. Young objects are collected more frequently, reducing overall GC work. - Continued removal of legacy features: Biased locking (disabled by default in Java 15, present in Java 17's codebase) is fully removed in Java 18. Security Manager is deprecated for removal. The ecosystem continues to modernize.
The JVM is not a black box. Every behavior described in this post can be observed, measured, and tuned. Tools like jcmd, jstack, jhsdb, JDK Flight Recorder (jfr), and async-profiler give you direct visibility into classloading, compilation, GC behavior, thread state, and memory layout. Understanding these internals transforms the JVM from an opaque runtime into a system you can reason about, debug, and optimize with confidence.