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.
See how HotSpot tiered compilation works in JDK 25, how to inspect warmup, and when JFR or compilation logs can guide tuning.
JIT Compilation Internals
This guide describes tiered compilation in the HotSpot server VM shipped with JDK 25. It covers the compiler’s broad execution modes and ways to investigate warmup; other JVMs and releases can behave differently.
Introduction
Tiered compilation balances quick compilation with later optimization. Warmup can matter for short-lived processes, but its effect depends on the application and the work it performs. Use measurements to find out whether compilation contributes to a latency or throughput problem.
When to Use JIT Knowledge
JIT compilation internals become relevant when you need to:
- Investigate startup latency: Compare cold-start and warmed measurements, then check whether compilation overlaps with slow requests
- Inspect runtime behavior: Use JFR or HotSpot compilation logs to see whether JIT activity lines up with a problem
- Compare JVM releases: Changes in compiler policy can affect warmup and steady-state performance
- Review the code cache: Check for compiler warnings before considering code-cache settings
When Not to Use
Most developers do not need to tune JIT options during normal development. Start with application-level profiling; investigate compiler behavior only when the measurements point there.
HotSpot Tiered Compilation in JDK 25
This overview describes the HotSpot server VM in JDK 25. Tiered compilation is enabled by default there. Other JVMs and releases can use different compilers, policies, and defaults.
HotSpot does not compile every method after a fixed number of calls. It uses runtime profiles and compilation levels to balance the cost of compiling with the benefit of faster code. A method may stay interpreted, run in C1-compiled code, or later be recompiled by C2. Not every method follows every step.
| Execution mode | Role |
|---|---|
| Interpreter | Runs bytecode and gathers runtime information |
| C1 compiler | Compiles quickly; some tiers collect profiling data |
| C2 compiler | Uses profiles for more aggressive optimization |
The compiler policy considers factors such as execution frequency and profile data. Exact thresholds and transitions are HotSpot implementation details. They are not stable invocation counts to calculate against or tune by default.
On-Stack Replacement
HotSpot can compile a loop while its method is already running and transfer execution into compiled code. This is called on-stack replacement (OSR). It helps long-running loops that would otherwise have to return before a regular method-entry compilation could take effect.
OSR decisions depend on the JVM’s compilation policy. A percentage flag or back-edge count is not a portable way to predict when it will happen.
Deoptimization
Compiled code can rely on assumptions drawn from observed types and branches. If later execution contradicts an assumption, the JVM can deoptimize: it returns execution to a less optimized form, updates its profiles, and may compile again. This is normal adaptive behavior. Repeated deoptimization is worth investigating only when a recording or compilation log shows that it affects the workload.
Code Cache Management
The JIT compiler stores all compiled native code in a region of memory called the code cache. Unlike the Java heap where objects live, the code cache holds raw machine instructions and associated metadata.
flowchart TD
subgraph JVMProcess["JVM Process Memory"]
direction TB
subgraph CodeCache["Code Cache"]
CODE["Generated machine code"]
META["Related metadata"]
end
end
Capacity and Diagnostics
HotSpot stores generated machine code and related metadata in the code cache. Its default capacity depends on the JDK release, VM mode, and configuration. The -XX:ReservedCodeCacheSize option sets an upper bound, but increasing it is only useful when evidence points to code-cache pressure.
When space runs low, HotSpot may reclaim eligible compiled code or stop compiling new methods, depending on the cache state and release. Do not assume that every full-cache warning disables all compiled code or causes a fixed throughput drop. Check the warning, JFR recording, and compilation output for the JVM you run.
Code Cache Flushing
HotSpot can reclaim code that is no longer in use. The exact policy and diagnostic messages are implementation details. If code-cache activity appears in a performance incident, reproduce the workload and compare recordings before changing code-cache options.
JIT Optimization Techniques
HotSpot can use runtime profiles when optimizing code. The transformations it applies depend on the code, observed profiles, compiler, and JDK release; these are not guarantees for a particular source construct.
Method Inlining
Inlining can remove call overhead and let the compiler optimize the caller and called method together.
// Before inlining
public double distance(Vector a, Vector b) {
return Math.sqrt(dx(a, b) + dy(a, b));
}
public double dx(Vector a, Vector b) { return a.x - b.x; }
public double dy(Vector a, Vector b) { return a.y - b.y; }
// After inlining (conceptually)
public double distance(Vector a, Vector b) {
return Math.sqrt((a.x - b.x) + (a.y - b.y));
}
Inlining replaces a call with the called method’s body. HotSpot’s decision depends on factors such as method size, call-site profile, and compilation budget. There is no fixed bytecode-size rule that predicts whether a method will be inlined; inspect compiler diagnostics for the JDK you run.
Escape Analysis
Escape analysis determines whether an object can be reached outside a local scope. If HotSpot proves that it does not escape, it may:
- Eliminate synchronization on an object that cannot be observed by another thread
- Scalar-replace the object by keeping its fields as separate values, which can remove the allocation
record Pair(int left, int right) {}
static int sum(int left, int right) {
Pair pair = new Pair(left, right);
return pair.left() + pair.right();
}
// HotSpot may scalar-replace pair; this is an optimization, not a promise.
Dead Code Elimination
Dead code elimination removes computations whose results cannot affect observable behavior. Profile data can also help HotSpot optimize a rarely used path, but that path must remain correct if it later executes; the JVM can deoptimize when a speculative assumption no longer holds.
A concrete example:
public void process(Point p) {
double temp = Math.sqrt(p.x * p.x + p.y * p.y); // computed
System.out.println("Processing point"); // result never used
}
Here temp is never read, so the computation has no observable result. A compiler may remove it. Avoid using code like this to benchmark a computation: the optimizer may remove work the benchmark does not consume.
The compiler can remove dead stores, fold constant expressions, and simplify branches when it can prove the result. A branch that was not taken during profiling is not necessarily deleted; the compiled code may guard the common case and deoptimize if later input takes a different path.
The compiler can also propagate constants and remove redundant loads or stores when the result is provable. It does not perform a general cleanup pass for every pattern in source code.
Static compilers can also use profile-guided optimization. A JIT can gather profiles while a process runs and revise compiled code when assumptions change, but it is not inherently faster than ahead-of-time code for every workload.
Loop Unrolling
Unrolling duplicates some loop work to reduce loop-control overhead and expose more instruction-level parallelism. It can also increase code size, so the compiler applies heuristics based on the loop and target platform.
Exact unrolling choices and related options vary by compiler and release. Check compilation diagnostics before changing an unrolling option.
Investigating Compilation-Related Symptoms
Startup or Warmup Regression
A slow first request is not enough to identify JIT compilation as the cause. Compare cold-start and warmed runs with the same workload. Use a JFR recording or HotSpot compilation log to check whether compilation overlaps with the delay, then repeat the measurement before changing flags.
Code Cache Warnings
Code-cache pressure can limit further compilation, but the effect depends on the HotSpot release and cache state. Check the warning and relevant runtime diagnostics before considering -XX:ReservedCodeCacheSize. The default varies by JDK and VM mode; do not increase it without evidence that code-cache pressure is the cause.
Repeated Deoptimization
HotSpot can deoptimize code when runtime behavior no longer matches a compiled assumption, then compile again using updated profiles. Look for repeated deoptimization in a recording or compilation log before attributing latency to it. Class loading, changing profiles, and other work can occur at the same time.
Latency During Compilation
Compilation uses CPU while application work is running, but a latency spike alone does not show that the compiler caused it. Record the application during the spike and compare compilation activity with request latency. Reproduce the same traffic pattern before considering compiler-thread options; additional compiler threads also use CPU.
Trade-Offs of Tiered Compilation
| Concern | What to expect |
|---|---|
| Startup | Compilation can add work during startup; impact depends on the process and workload |
| Throughput | HotSpot may optimize frequently executed code using runtime profiles |
| Memory | Compiled code uses memory outside the Java heap, including the code cache |
| Portability | Tiering, compiler options, and defaults vary across JVMs and releases |
Implementation Snippets
Record a Short Flight Recording
# HotSpot JDK 25; use a representative workload
java -XX:StartFlightRecording=filename=jit.jfr,settings=profile,duration=60s \
-jar app.jar
Open the recording in JDK Mission Control to inspect runtime activity. The profile setting can collect more data than the default recording, so use it for a short investigation.
Print HotSpot Compilation Activity
# Diagnostic output; format and options are release-specific
java -XX:+PrintCompilation -jar app.jar
Use this log to see compilation activity, not as a stable interface for scripts. Check the options for the exact HotSpot release.
Compare Warmup Runs
Keep the JDK build, input data, concurrency, and measurement window the same. Separate cold-start behavior from warmed measurements, repeat each run, and compare the latency or throughput that matters before changing an -XX option.
Observability Checklist
- Record the JDK vendor, version, and VM options
- Compare cold-start and warmed measurements with a repeatable workload
- Use JFR and, when needed, HotSpot compilation logs to correlate compiler activity with latency
- Check for code-cache warnings before changing its size
- Re-run the same benchmark after each configuration change
Security Notes
The JIT compiler is part of the trusted runtime and has received security fixes over time. Keep the JDK patched. Bytecode verification and the Java module system are not sandboxes for untrusted programs; use operating-system or container isolation for that purpose.
Common Pitfalls
- Assuming compilation always improves a workload: Measure startup and warmed behavior over the process lifetime.
- Changing flags based on generic thresholds: Compiler policies and option defaults vary by JVM and release.
- Treating compiler logs as a stable API: Use them to investigate a specific JDK; do not build cross-version tooling around their format.
- Comparing unlike benchmark runs: Keep inputs, concurrency, JDK, and warmup procedure consistent.
- Assuming a module boundary is a security sandbox: Isolate untrusted code outside the JVM process.
Quick Recap Checklist
- JIT compilation turns selected bytecode into native code at runtime
- This overview is pinned to HotSpot’s server VM in JDK 25
- Tiered compilation can use C1 for faster compilation and C2 for further optimization
- OSR can transfer a running hot loop into compiled code
- Runtime profiles and compilation policies vary; there is no portable fixed call-count threshold
- Compiled code uses the code cache
- Deoptimization lets the JVM recover when compiled assumptions no longer hold
- Use JFR, compilation logs, and repeatable benchmarks before changing
-XXoptions
Interview Questions
HotSpot uses runtime profiles and its compilation policy to select code for compilation. The exact triggers are implementation details; there is no stable invocation count that predicts compilation across releases.
Tiered compilation balances quick compilation with later optimization. HotSpot can use C1 to compile code and gather profiles, then use C2 to optimize selected hot code. The server VM enables tiered compilation by default in JDK 25.
No. A method can remain interpreted, be compiled at one level, or be recompiled as profiles change. The path depends on execution and HotSpot's policy.
On-stack replacement (OSR) lets HotSpot transfer a running method into compiled code, often when a loop becomes hot before the method returns. Its trigger and timing depend on the JVM policy.
Compiled code may rely on observed types or branch behavior. If later execution contradicts an assumption, HotSpot can deoptimize, resume in a less optimized form, update profiles, and compile again.
The code cache stores compiled machine code and related metadata. Its defaults and behavior vary by JDK and VM mode. Investigate code-cache warnings before changing its maximum size.
Use JFR for runtime data and, for HotSpot, compilation logs when you need method-level detail. These diagnostics can show whether compilation coincides with a measured issue; their event sets and output formats depend on the JDK release.
Do not start there. Compilation policy and threshold controls vary by JVM and release. First reproduce the behavior with a consistent workload, compare cold and warmed measurements, and use JFR or compilation logs to confirm that JIT activity is involved.
No. Compilation consumes CPU and can improve frequently executed code, but the benefit depends on process lifetime and workload. Measure startup and steady-state performance separately.
Runtime profiles, class loading, scheduling, and environmental conditions can differ between runs. Keep the JDK, inputs, concurrency, and measurement process consistent when comparing results.
Further Reading
- Method Invocation Bytecode — Internal link to related roadmap blog
- Tiered Compilation — Internal link to related roadmap blog
- GraalVM Native Image — Internal link to related roadmap blog
- HotSpot VM performance enhancements in JDK 25 — Tiered compilation overview
- JDK 25 java command reference — HotSpot options and compilation logging
- Oracle JFR diagnostic tools — Recording and inspecting runtime activity
- Advanced Java & JVM Internals Roadmap — Parent roadmap
Conclusion
HotSpot uses runtime profiles to balance quick compilation with later optimization. For a warmup or latency issue, record the same workload with JFR or a compilation log, then compare repeatable cold and warmed runs before changing JVM options. See Tiered Compilation for a closer look at the interpreter, C1, and C2.
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 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.
Tiered Compilation in the JVM
Explore C1 and C2 JIT compilers, on-stack replacement, and deoptimization handling in the JVM's tiered compilation model.