Execution Engine: Interpreter, JIT Compiler, and Garbage Collector
Deep dive into the JVM Execution Engine covering bytecode interpretation, JIT compilation, and Garbage Collector architecture and algorithms.
Deep dive into the JVM Execution Engine covering bytecode interpretation, JIT compilation, and Garbage Collector architecture and algorithms.
Execution engine: interpreter, JIT compiler, and garbage collector
The execution engine interprets bytecode, compiles hot methods, and works with the garbage collector to reclaim unreachable objects. This guide looks at those stages and at ways to diagnose performance on the JDK you deploy.
Introduction
The JVM runs bytecode in the execution engine. It interprets instructions at first and may compile frequently used methods to native code. The garbage collector reclaims objects that are no longer reachable.
A slow start can come from JIT warmup, and a latency spike can coincide with a GC pause. GC logs or a Java Flight Recorder capture help establish whether either explains a production problem. The sections below cover the interpreter, JIT compiler, and collector, with attention to the JDK release you deploy.
When not to use
If your application meets its latency and throughput goals, the JVM defaults may be enough. Do not switch collectors or disable tiered compilation without measurements showing a problem. Request rate alone does not determine whether a different collector will help.
Avoid JIT internals unless you are tracking down specific issues. Compilation thresholds, inline budgets, and escape analysis settings are JVM-specific and vary between versions. Time spent tuning -XX:CompileCommand flags is usually better spent improving your hot code paths or algorithmic complexity. The exception is when you have clear evidence from async-profiler, Java Flight Recorder, or GC logs that compilation is actually the problem.
Treat the collector selected by your JDK as a baseline, then measure the application under its real workload. Parallel GC may suit throughput-focused jobs; ZGC or Shenandoah may help when pause targets are tight, if your JDK distribution supports them. Each choice affects CPU use, memory headroom, and throughput. Runtime Data Areas and JVM Startup and Shutdown cover related memory and initialization topics.
Execution engine architecture
graph LR
Bytecode["Bytecode<br/>Instructions"]
subgraph "Execution Engine"
Interpreter["Interpreter"]
JIT["JIT Compiler<br/>Client/Server"]
GC["Garbage<br/>Collector"]
NMI["JNI/Native<br/>Interface"]
end
Bytecode -->|Hot Code| JIT
Bytecode -->|Cold Code| Interpreter
Interpreter -->|Profile| JIT
JIT -->|Native Code| Execution
Execution --> NMI
NMI --> GC
The interpreter
The interpreter reads bytecode instructions one at a time and executes them directly. When the JVM starts, it uses the interpreter for all code. Interpretation is fast to start but slow to execute because each instruction requires a lookup and dispatch cycle.
The interpreter performs a switch on the opcode and calls the appropriate implementation. This dispatch overhead adds up. A simple arithmetic operation might require dozens of JVM instructions just to fetch operands and store results.
The interpreter records profiling information: which methods are called frequently, which branches are taken, which types flow through each call site. This profiling data feeds the JIT compiler.
Tiered compilation
Modern JVMs use tiered compilation to balance startup speed and peak performance. Without it, the JVM faces a tradeoff: compile everything eagerly at startup and wait, or interpret everything and run slowly. Tiered compilation resolves this by compiling code incrementally, increasing optimization as methods prove themselves hot.
Tier 1: Interpreted bytecode. The JVM starts here because interpretation has zero compilation overhead. Code runs immediately, but each bytecode instruction requires a dispatch lookup on every execution. The interpreter also begins collecting profiling data from the first invocation: which methods are called repeatedly, which branches are taken, which receiver types flow through call sites.
Tier 2: Simple JIT compilation using the client compiler (C1). When a method’s invocation count crosses a threshold (typically 1000 calls), the JVM queues it for C1 compilation. C1 generates native code quickly with basic optimizations and limited type speculation. The compiled version replaces the interpreted version, giving you faster execution while the JVM keeps profiling.
Tier 3: Limited profiling JIT using the server compiler (C2). Methods that stay hot after C1 compilation accumulate more profiling data and eventually qualify for C2 compilation. C2 uses aggressive inlining based on the type profiles collected across many invocations. Compilation takes longer but produces faster code than C1.
Tier 4: Full optimization JIT (C2 with maximum optimization). In some JVM configurations, methods that remain hot after initial C2 compilation get recompiled again with more aggressive settings. This final tier extracts the last bit of performance from truly critical hot paths.
Promotion between tiers happens automatically based on invocation counts. The JVM tracks each method’s call frequency and kicks in the next compilation level once a threshold is crossed. Demotion happens when assumptions made during compilation break. If a method was compiled assuming a specific receiver type but a new class is loaded that changes that assumption, the JVM marks the compiled code as invalid and falls back to interpreted mode. This mechanism is called deoptimization, and it causes a brief performance dip while the method runs interpreted and the JIT queues a new compilation with updated profiling data.
Just-in-time compiler
The JIT compiler solves the interpretation bottleneck by compiling hot bytecode to native machine code at runtime. When a method is invoked many times, the JIT compiler spends time upfront compiling it, then all future calls run at native speed.
JIT compilation process
-
Profiling: The interpreter collects execution statistics. Which methods are hot? What types flow through each call site? Which branches are taken most frequently?
-
Compilation Request: When a method’s invocation count exceeds the JIT threshold, the compiler queues it for compilation.
-
Code Generation: The JIT compiler generates native machine code. Different JVMs use different compilers: HotSpot uses C1 (client) and C2 (server); GraalVM uses Graal as a modern alternative.
-
Installation: The compiled code replaces the interpreted version. Calls to this method now go directly to native code.
-
Deoptimization: If assumptions are violated (e.g., a class gets loaded that invalidates type speculation), the JVM can revert to interpreted mode.
JIT optimizations
The JIT compiler performs aggressive optimizations based on profiling data:
Inlining replaces method calls with the method body. This eliminates call overhead and enables further optimizations across method boundaries. The JIT inlines small methods and hot call sites automatically.
Dead Code Elimination removes code whose results are never used. If a computation is performed but its result is discarded, the JIT can eliminate the computation entirely.
Constant Folding evaluates constant expressions at compile time. If x is always 10, expressions like x + 5 become 15.
Loop Unrolling reduces loop overhead by performing multiple iterations per loop body evaluation. This reduces branching and enables vectorization.
Escape Analysis determines if an object escapes the method or thread. If an object does not escape, the JIT can allocate it on the stack instead of the heap, eliminating allocation and garbage collection overhead entirely.
Garbage collection architecture
The Garbage Collector automatically reclaims memory from objects that are no longer reachable. This eliminates dangling pointers and use-after-free bugs while reducing manual memory management burden.
GC roots
The GC identifies reachable objects by tracing from GC roots. GC roots are inherently reachable because they are the starting points of the object graph. The JVM maintains a set of root references that are always considered live. Anything not reachable from these roots through a chain of object references is eligible for reclamation.
Local variables and parameters on the JVM stack are the most common GC root type. Each thread has its own stack containing stack frames. When a method executes, its local variables and parameters are live on the stack. The GC treats these as roots whether they reference heap objects or primitives. Even if a local variable holds a reference to a massive object, that object is reachable as long as the variable itself is on the stack.
Active Java threads are always GC roots. The JVM maintains thread objects that represent running threads. The stack of each running thread contains references to objects currently in use. Threads that are blocked or waiting are also GC roots because their stacks hold local variable state that must remain valid.
Static variables are references stored in class metadata. When a class is loaded, the JVM creates a class object that holds references to static fields. These static references persist for the lifetime of the class (typically the lifetime of the JVM unless custom classloaders are used). Classes themselves can become unreachable if no other code references them and their classloader is collected; at that point, their static fields are also eligible for GC.
JNI references are pointers to Java objects from native code. When native code calls into Java through JNI, it can hold references to objects on the heap. JNI local references are scoped to the native method invocation; JNI global references persist until explicitly freed with DeleteGlobalRef.
Exception objects currently being thrown are GC roots while they propagate up the stack. When an exception is thrown, the JVM creates an exception object and stores a reference to it in a per-thread exception slot. This reference keeps the exception object reachable as it moves up the call stack through successive catch blocks, ensuring that if debugging is enabled, the full stack trace is available.
Anything not reachable from GC roots through object references is garbage. The GC traces through all live references starting from these root types, marking every reachable object. Unmarked objects are compacting candidates.
GC algorithms
Modern JVMs offer several GC algorithms, each optimized for different workload characteristics:
Serial GC uses a single thread for all GC work. It stops the world (STW) during collections. Appropriate for small heaps and single-threaded applications. Enabled with -XX:+UseSerialGC.
Parallel GC (Throughput GC) uses multiple threads and is designed to favor throughput. It may suit batch workloads that can tolerate pauses; measure it against the application’s latency and throughput targets. Enable it with -XX:+UseParallelGC.
CMS (Concurrent Mark Sweep) is historical. It was deprecated in JDK 9 and removed in JDK 14, so -XX:+UseConcMarkSweepGC is not a collector option on current JDKs. See JEP 363.
G1 (Garbage First) divides the heap into regions and selects regions for collection. In HotSpot, G1 became the default in JDK 9 and remains the default on most current configurations. Its pause-time goal is a heuristic, not a guarantee. Enable it with -XX:+UseG1GC.
ZGC and Shenandoah do much of their work concurrently and can suit workloads with tight pause goals. Their availability depends on the JDK vendor and build, and pause times are not guaranteed for every workload. Check the JDK’s collector documentation and benchmark before switching.
Collector availability by JDK version
Collector names and defaults vary by JDK release and distribution. This short history is a reminder to check the runtime you deploy:
| JDK release | Collector notes |
|---|---|
| JDK 8 | HotSpot included Serial, Parallel, G1, and CMS; availability varied by distribution. |
| JDK 9–13 | HotSpot made G1 the default. CMS was deprecated in JDK 9; Serial and Parallel remained available. |
| JDK 14–24 | CMS was removed in JDK 14. ZGC and Shenandoah availability depends on the JDK distribution and release. |
| JDK 25 | Oracle HotSpot documents Serial, Parallel, G1, and ZGC. Check the available collectors for your distribution. |
For migration details, see the JDK 25 migration guide. JEP 363 documents CMS removal in JDK 14.
GC phases
Most GC algorithms work in phases that alternate between stop-the-world pauses and concurrent execution. Each phase has a different impact on your application’s latency.
Mark is the first active phase of garbage collection. The GC starts from GC roots and traverses the entire object graph, marking every reachable object as live. In a stop-the-world collector, application threads are halted during marking to ensure consistency. In a concurrent collector like G1 or ZGC, marking runs alongside application threads, letting the application continue while the GC traces references. Marking time is proportional to the size of the live object graph, not the heap. A heap with 10GB allocated but only 2GB reachable still requires tracing through the 2GB of live objects.
Remark completes marking by handling edge cases introduced by concurrent execution. When the application runs concurrently with marking, it can modify the object graph by creating new references or breaking existing ones. The GC tracks these modifications using write barriers. Remark pauses application threads to reprocess objects changed during concurrent marking. This gives the mark phase a consistent view of the object graph. Current concurrent collectors have their own pause phases; CMS had a remark phase on older JDKs.
Sweep reclaims memory from unreachable objects. The GC scans through heap regions and identifies memory addresses that are not marked as live. This free memory is available for allocation but may be fragmented. Sweep runs concurrently in many modern collectors, meaning application threads keep running. However, sweeping concurrent with application threads requires synchronization because allocations can happen at the same time.
Compact moves surviving objects to reduce fragmentation. Moving objects requires updating references, so the cost and pause behavior depend on the collector. G1 evacuates selected regions; ZGC and Shenandoah relocate objects concurrently with brief synchronization phases. CMS did not compact during its normal concurrent sweep and could encounter fragmentation; CMS details apply to older JDKs only.
Young vs. old generation GC
Minor GC (young GC) collects the young generation. It is usually fast because the young generation is small and most objects are short-lived. Minor GC is stop-the-world but brief.
Major GC (old GC) collects the old generation. It is slower because the old generation is larger. The G1 algorithm refers to “mixed GC” when it collects both young and old regions.
Full GC is a collection of the entire heap, but its meaning depends on the collector and trigger. It can follow allocation pressure, metadata pressure, an explicit request, or other runtime conditions. A long or frequent full collection deserves investigation; a single event alone does not prove a leak or undersized heap.
Production failure scenarios
| Scenario | Root Cause | Symptoms | Resolution |
|---|---|---|---|
| GC Thrashing | Heap too small, excessive short-lived objects | High CPU, frequent GC, application pauses | Increase heap, optimize allocation patterns |
| Long GC Pauses | Allocation pressure, memory pressure, or a collector pause | Latency spikes, timeouts | Correlate GC logs/JFR with allocation and host metrics; test a supported collector only against a measured target |
| JIT Compilation Overhead | Excessive hot methods, compilation queue backlog | Sudden CPU spikes during warmup | Tiered compilation flags, increase code cache |
| Deoptimization Storms | Volatile type assumptions, class loading patterns | Performance instability | Reduce dynamic class loading, stabilize types |
| Metaspace GC Pressure | Classloader churn | High GC CPU, metaspace growth | Audit classloader lifecycle, limit dynamic proxies |
| Direct Buffer Memory Exhaustion | Excessive NIO buffer allocation | Native OOM, disk swap | -XX:MaxDirectMemorySize, audit ByteBuffer usage |
Trade-off analysis
| Trade-off | Considerations |
|---|---|
| Throughput vs. Latency | Parallel GC may favor throughput; G1, ZGC, and Shenandoah have different pause and CPU trade-offs. Measure the target workload. |
| Memory Footprint vs. Fragmentation | Compacting collectors eliminate fragmentation but use extra memory and CPU. Non-compacting collectors are faster but cause fragmentation. |
| JIT Compilation Time vs. Run Time | More aggressive JIT compilation improves peak performance but increases startup time and memory usage. |
| Young vs. Old Collection | Frequent young collection is cheap but promotes objects prematurely. Rare old collection is expensive when it happens. |
| Concurrent vs. Stop-The-World | Concurrent GC reduces pause times but uses CPU that could run application code. STW pauses are brief but still disruptive. |
Failure scenarios deep dive
Deoptimization storms in polymorphic sites
When a method call site is polymorphic (calling different implementations based on receiver type), the JIT compiler initially generates monomorphic code assuming a single type. If multiple new types appear at that call site, the JIT must deoptimize and fall back to megamorphic dispatch, which is slower. This can cause “deoptimization storms” when class loading is uneven or when libraries dynamically generate proxy classes. Monitoring deoptimization counts with -XX:+PrintDeoptimization helps identify affected sites. The fix involves reducing dynamic proxy generation or forcing megamorphic dispatch earlier using @ForceInline hints.
Deoptimization storms manifest as a specific performance pattern: the application runs smoothly for a period, then suddenly degrades for a burst of time, then recovers. This cycle repeats as the JIT recompiles with new type feedback, deoptimizes when more types arrive, and recompiles again. You can spot this in Java Flight Recorder data by looking for the Deoptimization event, which records the reason for each deoptimization and the method affected. A healthy long-running application should have deoptimizations concentrated in the warmup phase; a steady stream of deoptimizations in production is a red flag.
The root cause is usually dynamic proxy generation. Libraries like Hibernate, Spring’s AOP, and serialization frameworks that emit proxy classes at runtime create many unique types at call sites that the JIT initially assumed would be monomorphic. Each new proxy type invalidates the JIT’s assumption, triggering deoptimization. ORM query results returned through generic interfaces are a common culprit. If your application uses bytecode manipulation frameworks, you should pre-warm the JIT by forcing those code paths to execute during startup before they face production traffic.
The fix involves either eliminating the polymorphism or teaching the JIT to handle it more gracefully. Reducing dynamic proxy generation is the first option: refactor hot paths to use concrete types instead of interfaces where possible, and audit your dependency injection and AOP configuration to ensure you are not generating more proxies than necessary. Forcing megamorphic dispatch earlier is the second option: the @ForceInline hint applied to the callee forces inlining even at megamorphic call sites, while @DontInline on the caller prevents inlining that would later deoptimize. You can also use -XX:TypeProfileWidth=2 to widen the JIT’s type profile, though this is a JVM internal flag. A different compiler may behave differently; profile before considering a runtime change.
Historical example: CMS failures on older JDKs
CMS failure messages such as concurrent mode failure and promotion failed appear in logs from older JVMs. CMS was removed in JDK 14, so its flags and tuning values do not apply to current JDKs. If you maintain a pre-14 runtime, use documentation for that exact release; for a current runtime, investigate its GC logs and JFR events instead of applying CMS-specific fixes.
ZGC heaps larger than available physical memory
ZGC supports large heaps, but a heap that competes with the operating system and other processes for physical memory can still cause paging and latency. Check the full process footprint, not just -Xmx, and leave enough memory for metaspace, code cache, thread stacks, direct buffers, and the OS. Compare the result with the application’s memory and pause goals before choosing ZGC over another collector.
The risk is not unique to ZGC: paging can stall application threads and concurrent GC work. If pauses rise alongside swap activity, correlate GC logs with operating-system memory and paging metrics before blaming the collector.
Look for correlated evidence: GC pause events, process memory, page faults, and swap activity from tools such as vmstat. A pause spike alongside paging points to memory pressure, though it does not by itself identify the collector as the cause.
If the process is paging, reduce the total memory footprint or add capacity, then repeat the same load test. There is no universal percentage of host memory to reserve; include the JVM’s non-heap memory and other workloads in the budget. Compare another supported collector only if the measured pause or throughput target still is not met.
Implementation patterns
// Forcing GC (not recommended for production, but useful for testing)
public class ForceGC {
public static void main(String[] args) {
// Make objects eligible for collection
byte[] bigArray = new byte[1024 * 1024];
bigArray = null;
// Request GC
System.gc(); // Hint to JVM, may be ignored
// Better: run finalization
System.runFinalization();
}
}
// Soft references for caches (auto-reclaimed before OOM)
import java.lang.ref.SoftReference;
public class SoftReferenceCache<K, V> {
private final Map<K, SoftReference<V>> cache = new HashMap<>();
public V get(K key) {
SoftReference<V> ref = cache.get(key);
return ref != null ? ref.get() : null;
}
public void put(K key, V value) {
cache.put(key, new SoftReference<>(value));
}
public void clear() {
cache.clear();
}
}
// Weak references for canonical mappings (reclaimed on GC)
import java.lang.ref.WeakHashMap;
public class WeakCache<K, V> {
// Keys are weakly referenced - GC reclaims entry when key is weakly reachable
private final WeakHashMap<K, V> cache = new WeakHashMap<>();
public V get(K key) {
return cache.get(key);
}
public void put(K key, V value) {
cache.put(key, value);
}
}
// Phantom references for cleanup actions (reclaimed after finalization)
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
public class ResourceCleanup {
public static void main(String[] args) {
ReferenceQueue<MyResource> queue = new ReferenceQueue<>();
PhantomReference<MyResource> ref = new PhantomReference<>(
new MyResource(), queue);
// When MyResource is GC'd (after finalization),
// the phantom reference is enqueued
System.gc();
// Check queue for cleanup
PhantomReference<MyResource> polled = (PhantomReference<MyResource>) queue.poll();
if (polled != null) {
// Clean up native resources
polled.clear();
}
}
}
Observability checklist
- Enable GC logging:
-Xlog:gc*:file=gc.log:time,uptime,level,tags - Monitor pause times vs. latency SLAs
- Track allocation rates (bytes/second promoted to old gen)
- Monitor JIT compilation time and code cache size
- Use jstat to track GC statistics:
jstat -gcutil <pid> 1000 - Monitor deoptimization counts
- Watch old-generation occupancy and collection causes for the collector used by this JDK
- Track metaspace reclamation after classloader cleanup
Capture a baseline on the JDK you deploy. Unified GC logging and JFR can record the same run:
java -Xlog:gc*:file=gc.log:time,uptime,level,tags \
-XX:StartFlightRecording=filename=gc.jfr,settings=profile,duration=5m \
-jar app.jar
jfr print --events jdk.GarbageCollection,jdk.GCPhasePause gc.jfr
When considering a different collector, hold the JDK build, heap limit, and representative request mix steady. Compare pause percentiles, throughput, CPU, allocation rate, and memory use against the same service targets. Change one setting at a time, and keep the default if the candidate does not improve a measured problem.
- Use async-profiler or Java Flight Recorder for detailed analysis
Security notes
JIT compilation introduces a security consideration: JIT compilers generate code at runtime. If an attacker can influence what code gets JIT compiled (through polymorphic call patterns, for example), they might be able to trigger generation of specific code sequences. Modern JVMs include protections against JIT spraying attacks.
The GC does not automatically sanitize memory. If you store sensitive data in objects and rely on GC to “erase” it, you may be disappointed. The GC reclaims the memory but does not overwrite it. Use explicit clearing (setting byte arrays to zero) for sensitive data that must not be accessible after use.
Common pitfalls / anti-patterns
Assuming System.gc() forces garbage collection. System.gc() is only a hint to the JVM. The JVM may ignore it entirely. In production, never rely on System.gc() to manage memory.
Setting heap too small based on visible memory usage. The JVM uses more memory than the heap. Metaspace, code cache, thread stacks, native memory allocations, and internal JVM data structures all consume memory outside the heap.
Ignoring GC logs. GC logs help diagnose performance issues. They show pause times, allocation rates, and promotion patterns. Enable them in production.
Over-tuning GC parameters. Modern JVMs auto-tune well. Start with defaults and only tune after measuring. Premature tuning based on intuition often makes things worse.
Assuming more threads means better parallel GC performance. Parallel GC threads compete for CPU. Too many threads cause context switching overhead that outweighs parallelism benefits.
Treating one collector as best for every workload. Defaults and available collectors vary by JDK. A throughput-focused job may benefit from Parallel GC, while ZGC or Shenandoah may help with a tight pause target. Measure the same workload before changing.
Quick recap checklist
- Interpreter runs bytecode initially, JIT compiles hot code to native
- Tiered compilation balances startup speed and peak performance
- JIT optimizations include inlining, dead code elimination, escape analysis
- GC reclaims unreachable objects automatically
- GC roots include stack variables, statics, active threads, JNI refs
- Serial GC is single-threaded; Parallel uses multiple threads
- G1 divides heap into regions, aims for pause time goals
- Confirm the selected collector is available in this JDK build and compare its measured pauses and throughput
- Young GC collects short-lived objects; old GC collects long-lived ones
- System.gc() is only a hint, not a command
- Different GC algorithms prioritize different aspects (throughput vs. latency)
Interview questions
Interpretation executes bytecode by reading each instruction and performing the corresponding action through a switch on the opcode. It has zero compilation overhead, so it starts fast, but each instruction incurs dispatch overhead. JIT compilation translates hot bytecode methods to native machine code at runtime. The first invocation is slow (compilation takes time), but subsequent calls run directly on the CPU without interpretation overhead. Modern JVMs use tiered compilation: interpreted code runs initially while the JIT compiler queues methods for compilation. Hot methods get compiled multiple times with increasing optimization levels.
Escape analysis determines whether an object escapes the method or thread in which it was created. If an object does not escape (its reference is never stored somewhere that outlives the method, like a static field or returned from the method), the JIT compiler can perform optimizations. Most importantly, it can allocate the object on the stack instead of the heap. Stack allocation is faster (no atomic CAS operation needed) and eliminates garbage collection overhead for that object entirely. The object simply disappears when the method returns. This optimization is particularly powerful for small, short-lived objects inside hot methods.
Serial GC uses one thread and stops application threads during collection. Parallel GC uses multiple GC threads and is aimed at throughput. G1 collects selected heap regions and works toward a pause-time goal while maintaining throughput. CMS ran much of its marking concurrently, but it was deprecated in JDK 9 and removed in JDK 14; its flags are only relevant when maintaining an older runtime. Check collector availability and defaults for the JDK distribution you deploy.
GC thrashing happens when the heap is too small for the application's allocation rate. The JVM spends most of its time in GC, with young generation filling up immediately after each collection. Objects get promoted to old generation prematurely because they do not survive enough young collections. The fix involves increasing heap size (-Xmx), optimizing object allocation patterns to create fewer short-lived objects, choosing a different GC algorithm, or fixing memory leaks. Profile the application's allocation rate and set heap size to accommodate 2-3 young generations worth of allocation between young GCs.
Young and old collections describe different parts of the heap, though exact terminology varies by collector. G1 mixed collections include young regions and selected old regions. A full GC collects the heap and may also involve class metadata reclamation. A long or repeated full collection is worth investigating, but one event can have several triggers, including allocation pressure, metadata pressure, or an explicit request; it does not by itself prove a leak.
Tiered compilation works in stages. When an application starts, the JVM uses the interpreter (Tier 1) to execute bytecode immediately without compilation overhead. As methods become hot (invocation count exceeds thresholds), the client JIT compiler (C1) compiles them quickly with basic optimizations (Tier 2), providing faster execution while still profiling. Methods that remain hot are eventually compiled by the server JIT compiler (C2) with aggressive optimizations (Tier 3/4), producing peak performance. This approach avoids the warmup delay of waiting for full server compilation while still achieving high performance for sustained hot methods. The JVM automatically promotes and demotes methods between tiers based on invocation counts and profiling data.
ZGC and Shenandoah perform much of their work concurrently, but their availability and implementation details depend on the JDK vendor and release. Neither promises the same pause time on every heap and workload, and both trade some CPU or memory for concurrent work. Check the collector guide for your JDK, run the same application workload with each supported option, and compare pause percentiles, throughput, and resource use.
JIT compilation is CPU-intensive work. When a hot method's invocation count exceeds the JIT threshold, the compiler thread(s) spend significant CPU time generating native code. With multiple methods crossing the threshold simultaneously (common after application startup or during request spikes), the compilation queue backs up and the compiler threads compete with application threads for CPU. The result is a sudden CPU spike that coincides with the JIT compilation activity. Mitigation strategies include: pre-warming methods during startup with replay-compilation files, using `-XX:+TieredCompilation` to spread compilation across more tiers with lower thresholds, increasing the code cache size with `-XX:ReservedCodeCacheSize`, or reducing the number of hot methods through code optimization.
Escape analysis determines if an object escapes a method or thread. If an object does not escape, the JIT compiler can apply several optimizations. Lock elision (also called lock bypassing) occurs when an object is proven to be thread-local, meaning the lock on it can never be contended. The JIT removes the lock operation entirely, eliminating atomic operations and memory barriers. Scalar replacement replaces an object allocation with its component fields, allocating them as local variables instead. Stack allocation places the object on the stack instead of the heap, making it disappear automatically when the method returns. These optimizations compound: escape analysis enables lock elision, which can enable further inlining, which enables more escape analysis, forming an optimization loop.
These reference types form a hierarchy of "reachability" from strongest to weakest. A soft reference is cleared at the JVM's discretion when memory is low. The GC will only reclaim soft references if the application is about to run out of memory. Use soft references for caches where you want memory-sensitive eviction. A weak reference is cleared as soon as the GC detects the referent is no longer strongly or softly reachable. The next GC cycle reclaims the object. Use WeakHashMap for canonicalizing mappings (like intern pools) where you want the entry removed when no other references exist. A phantom reference is never automatically cleared. The GC enqueues phantom references to a ReferenceQueue after the referent's memory is reclaimed (after finalization if applicable). Use phantom references for performing cleanup actions after an object is about to be reclaimed.
GC logs record collection events, timing, memory before and after, and pause duration. A typical entry shows the GC type (young, mixed, full), the collector, heap usage, promotion amounts, and pause time. With -Xlog:gc*:file=gc.log:time,uptime,level,tags, logs include timestamps and uptime. GC logs reveal patterns: frequent young GC with low reclaim rates indicates allocation issues; long pauses call for checking pause causes and workload; steady heap growth needs heap and allocation analysis before diagnosing a leak. Always enable GC logs in production for incident investigation.
G1 accepts a pause-time goal through -XX:MaxGCPauseMillis, but the value is a heuristic, not a deadline. G1 selects collection sets and adjusts work toward the goal; actual pauses depend on the heap, live data, allocation rate, and host. G1 is the default in many HotSpot configurations and is a reasonable baseline, but compare measurements before concluding that it fits a particular workload.
Card marking is a technique used in generational collectors to efficiently track old-to-young generation references (which matter for major GC marking). Rather than scanning all old generation objects, the heap is divided into "cards" (typically 512 bytes). When a reference from old generation to young generation is written, the JVM marks the corresponding card as "dirty." During young GC, only dirty cards need to be scanned to find cross-generation references that root from old generation. This reduces scanning work. The card table is a byte array indexed by heap address ranges. Actual minor-GC pause times still depend on the collector and workload.
In older CMS logs, "promotion failed" meant CMS could not find contiguous old-generation space for an object promoted from the young generation, so the JVM could fall back to a full collection. CMS was removed in JDK 14. On a current JDK, first identify the active collector and inspect GC logs or JFR for allocation pressure, old-generation occupancy, and pause causes. Do not apply CMS tuning flags to another collector.
C1 (client compiler) focuses on fast compilation with basic optimizations, suitable for short-running applications where quick startup matters. It uses simpler heuristics and less aggressive inlining. C2 (server compiler) performs more intensive optimizations, including inlining, escape analysis, loop optimization, and speculation. It takes longer to compile and uses more resources, but can produce faster native code for long-running hot methods. In tiered compilation, methods start with C1 and may move to C2 as they stay hot.
Objects with finalize() methods are treated specially: after GC determines an object is unreachable, it is put on a queue for finalization. The finalizer thread runs finalize() methods asynchronously. Only after finalization does the object's memory become reclaimable. This delays reclamation: finalizable objects linger at least one GC cycle longer. If a finalizer stores a reference to the dying object where other code can reach it, the object becomes reachable again. Because of these quirks and performance costs, avoid finalizers; use try-with-resources or Cleaner for cleanup instead.
GC ergonomics is the JVM's self-tuning mechanism for GC. When -XX:+UseAdaptiveSizePolicy is enabled (default for G1 and Parallel GC), the JVM automatically adjusts heap sizes, young/old generation ratios, Survivor space sizes, and tenuring thresholds based on actual GC behavior and application behavior. It aims to meet user-specified pause time goals (-XX:MaxGCPauseMillis) or maximize throughput (-XX:GCTimeRatio). Ergonomics allows the JVM to adapt to workload changes without manual tuning. For most applications, letting ergonomics work without manual intervention produces reasonable results.
Stop-the-world phases pause application threads; concurrent phases let them continue while GC work proceeds. Serial and Parallel GC rely more heavily on stop-the-world work, while G1, ZGC, and Shenandoah perform some work concurrently. Concurrent collectors still need synchronization pauses, and their CPU use and pause times vary by JDK, heap, and workload. Compare measured results rather than assuming a collector guarantees a particular latency.
In G1, objects larger than 50% of a region size are called "humongous" and handled specially. Instead of being allocated in a regular region, they are allocated in a contiguous set of humongous regions. G1 must scan these regions during young GC and remark phases, and they are reclaimed with a special "humongous reclamation" that scans all regions in the set. If humongous objects are frequently allocated and freed, they cause fragmentation and increase pause times because G1 cannot efficiently evacuate them like regular objects. Applications with many large short-lived objects (like large caches) may experience G1 performance degradation.
The JIT compiler inlines methods by replacing call instructions with the method's bytecode body, eliminating call overhead (stack frame setup, parameter passing, return handling). Inlining enables other optimizations that span method boundaries. The JIT uses several criteria: method size (small methods are always inlined), call site frequency (hot call sites are aggressively inlined), and heuristics for virtual calls (monomorphic calls are inlined directly; megamorphic calls use type profile). Limits include the inline budget (too much inlined code exceeds code cache), method complexity (loops and recursion are rarely inlined), and compilation level (C2 inlines more aggressively than C1). The @ForceInline annotation forces inlining; @DontInline prevents it.
Further reading
- JVM Architecture Overview - How the execution engine fits into the JVM
- Runtime Data Areas - Memory regions the execution engine reads from and writes to
- Class Loader Subsystem - How classes are loaded and initialized before execution
- JVM Startup and Shutdown - How the JIT compiler warms up during startup
- JVM Bytecode Verification - Why the verifier must pass before code executes
- Advanced Java & JVM Internals Roadmap - Structured learning path
- JEP 363: Remove the Concurrent Mark Sweep (CMS) Garbage Collector - CMS removal in JDK 14
- JDK 25 Garbage Collection Tuning Guide - Collector availability and selection guidance
- JDK 25 Migration Guide - Changes when moving from JDK 8 to later releases
Conclusion
The execution engine interprets bytecode, compiles hot methods, and works with the garbage collector. CMS was removed in JDK 14. Start with the collector selected by your JDK, then compare JFR and GC-log measurements against your latency, throughput, CPU, and memory goals.
Category
Related Posts
Deoptimization Debugging: When JIT Compiled Code Reverts
Learn what causes the JVM to deoptimize JIT-compiled code, how to detect deoptimization events, and how to fix the underlying issues.
JIT Compilation Internals
See how HotSpot tiered compilation works in JDK 25, how to inspect warmup, and when JFR or compilation logs can guide tuning.
JIT Optimization in Java: Inlining and Escape Analysis
See how HotSpot handles inlining, escape analysis, scalar replacement, and dead code elimination, and how to inspect JIT behavior.