Sub topic 14
The code cache
Where compiled code lives
When C1 or C2 finishes compiling a method, the native machine code has to be stored somewhere the JVM can jump to it. That place is the code cache. It is a region of native memory, separate from the Java heap, that holds compiled methods and the runtime stubs the JVM generates for itself. Because it sits outside the heap, -Xmx does not limit it and the garbage collector does not manage it.
This chapter assumes you know the tier levels 0 to 4 and the compile queue from the earlier chapters. The code cache is the third limited resource in the JIT pipeline, after compiler threads and the compile queue. Its limit is a fixed size, and when it fills up the effects are severe, so it is worth understanding.
What is stored in it
The code cache holds three kinds of content:
- nmethods: native code for one compiled Java method, produced at tier 1, 2, 3 or 4. An nmethod also carries metadata such as the deoptimization information and the dependencies the compiler assumed.
- Adapters: small pieces of code that translate between the interpreter's calling convention and compiled code's calling convention.
- Interpreter and stubs: the template interpreter itself, plus runtime stubs for things like allocation and exception dispatch.
The segmented code cache
Before JDK 9 the code cache was one block. JDK 9 (JEP 197) split it into three code heaps. JDK 11 does this by default when tiered compilation is on and the reserved size is at least 240 MB, which is the default with tiered compilation.
| Code heap | Contents | Tiers stored | Default sizing |
|---|---|---|---|
| non-nmethods | Interpreter, stubs, adapters, buffers | Not applicable | About 5 MB |
| profiled nmethods | Lightly optimized code that collects profiles | 2 and 3 | Half of the remainder |
| non-profiled nmethods | Fully optimized or trivial code | 1 and 4 | Half of the remainder |
The split has two benefits. Short-lived tier 3 code, which is replaced soon after it is written, no longer sits between long-lived tier 4 code and fragments it. Related code also stays close together in memory, which helps the CPU's instruction cache and makes sweeping cheaper.
If one heap fills while another has room, the VM can place an nmethod in a neighbouring heap instead of failing. Do not rely on this when sizing, though. The total size is still the limit.
Sizing flags
| Flag | Meaning |
|---|---|
| `-XX:ReservedCodeCacheSize=<size>` | Total address space reserved. Default 240 MB with tiered compilation, 48 MB without it. |
| `-XX:InitialCodeCacheSize=<size>` | Memory committed at startup. The cache grows toward the reserved size. |
| `-XX:+/-SegmentedCodeCache` | Force segmentation on or off. |
| `-XX:NonNMethodCodeHeapSize`, `-XX:ProfiledCodeHeapSize`, `-XX:NonProfiledCodeHeapSize` | Size individual heaps. Rarely needed. |
| `-XX:+/-UseCodeCacheFlushing` | Allow the sweeper to remove unused nmethods. On by default. |
Reserving address space is cheap. The operating system only backs the cache with physical memory as it is committed, so a larger ReservedCodeCacheSize costs little until the code is generated.
Note that -XX:TieredStopAtLevel=1 and -XX:-TieredCompilation change the default size and segmentation. Always check the output of -XX:+PrintCodeCache after changing compilation modes.
Inspecting usage
You can look at the code cache in three ways. The first is -XX:+PrintCodeCache, which prints a summary when the JVM exits:
java -XX:+PrintCodeCache HotLoopThe output looks roughly like this. Your sizes and addresses will differ.
CodeHeap 'non-profiled nmethods': size=120032Kb used=95Kb max_used=95Kb free=119936Kb
bounds [0x00007f..., 0x00007f..., 0x00007f...]
CodeHeap 'profiled nmethods': size=120028Kb used=412Kb max_used=412Kb free=119615Kb
bounds [0x00007f..., 0x00007f..., 0x00007f...]
CodeHeap 'non-nmethods': size=5700Kb used=1130Kb max_used=1150Kb free=4569Kb
bounds [0x00007f..., 0x00007f..., 0x00007f...]The second is jcmd, which queries a running JVM without a restart:
jcmd <pid> Compiler.codecacheThe third is the JMX memory pools. The program below prints each code heap's usage using only the standard java.lang.management API:
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
public class CodeCacheInfo {
static int work(int x) {
return (x * 31) ^ (x >>> 3);
}
public static void main(String[] args) {
int acc = 0;
for (int i = 0; i < 20_000_000; i++) {
acc += work(i);
}
System.out.println("acc=" + acc);
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
String name = pool.getName();
if (name.startsWith("CodeHeap") || name.equals("Code Cache")) {
long usedKb = pool.getUsage().getUsed() / 1024;
long maxKb = pool.getUsage().getMax() / 1024;
System.out.printf("%-35s used=%7d KB max=%7d KB%n", name, usedKb, maxKb);
}
}
}
}On a default JDK 11 run you should see three CodeHeap pools. If you start with -XX:-SegmentedCodeCache, you should see a single pool named Code Cache. The same pools are visible in tools such as JConsole and VisualVM, which is the usual way to chart code cache usage over time in a long-running service.
Reclaiming space: nmethod lifecycle and the sweeper
Compiled code is not permanent. An nmethod moves through states:
- In use: callers can enter it.
- Not entrant: no new calls may enter it. This is what
made not entrantmeans in-XX:+PrintCompilation. Threads already executing it can finish or deoptimize. - Zombie: no activation remains, and the memory can be freed.
A background sweeper thread scans the cache and frees zombie nmethods. With UseCodeCacheFlushing enabled, it also removes nmethods that have not been used for a while, especially when free space is low. The tier 3 version of a method is usually made not entrant once tier 4 code replaces it, so its space returns to the profiled heap. Classes that get unloaded also cause their nmethods to be released.
The sweeper is a feature of the JDK 11 era. Later JDK releases changed how reclamation works, so treat these details as specific to the version this tutorial targets.
When the code cache fills up
If the VM cannot allocate space for new code, you see a message like this:
OpenJDK 64-Bit Server VM warning: CodeCache is full. Compiler has been disabled.
OpenJDK 64-Bit Server VM warning: Try increasing the code cache size using -XX:ReservedCodeCacheSize=After this, no new methods are compiled. Anything not already compiled stays in the interpreter, which is many times slower. The result looks like a performance regression that appears after the application has run for a while, and CPU usage often goes up while throughput goes down. The JVM does not crash and the output is correct, so the failure is easy to miss.
Typical causes are:
- Very large applications with many classes, such as application servers with many deployed modules.
- Heavy generated code, such as dynamic proxies, scripting engines and large generated parsers.
- Repeated deoptimization and recompilation of the same methods.
- A limit set too low, for example
-XX:ReservedCodeCacheSize=32mcopied from a small embedded config.
A reasonable procedure is:
- Run with
-XX:+PrintCodeCacheor watch the JMX pools under realistic load. - Compare
max_usedwith the heapsize. If usage stays under about 70 to 80 percent, no change is needed. - If a heap is near full, raise
-XX:ReservedCodeCacheSize(for example256mor512m) and measure again. - Check whether churn is the real cause, using
-XX:+PrintCompilationto look for repeatedmade not entrantlines on the same methods.
Do not set the cache huge by default. A larger cache also means more compiled code in memory, with worse locality and more native memory used, and it can hide a problem that should be fixed elsewhere.
Summary of cache-related behaviours
- The code cache is native memory outside the heap, with a fixed reserved size.
- JDK 11 splits it by default into non-nmethods, profiled and non-profiled heaps.
- Tier 2 and 3 code goes to the profiled heap. Tier 1 and 4 code goes to the non-profiled heap.
- Not-entrant nmethods become zombies and are reclaimed by the sweeper.
- A full cache stops compilation and leaves new hot code in the interpreter.
Exercise
A service runs fine for several hours on JDK 11, then throughput drops and CPU rises. Heap usage and GC logs look normal. The logs contain "CodeCache is full. Compiler has been disabled." Explain why this slows the application, name two ways to investigate, and describe the first change you would try.
Show answer
Once the cache is full, the JIT stops compiling, so any method not already compiled keeps running in the interpreter, which is much slower than native code. This explains rising CPU with falling throughput while the heap looks normal. To investigate, use -XX:+PrintCodeCache (or jcmd <pid> Compiler.codecache) to see how full each heap is, and use the JMX memory pools named CodeHeap '...' to chart usage over time. -XX:+PrintCompilation can also show whether the same methods are repeatedly made not entrant and recompiled. The first change is to raise -XX:ReservedCodeCacheSize, for example from the default 240m to 512m, and re-measure. If usage still climbs to the limit, look for the source of code churn such as generated classes or repeated deoptimization.
Exercise
In a segmented code cache, into which heap does a tier 3 compilation of a method go, and into which heap does the tier 4 version of the same method go? Why is this split useful?
Show answer
The tier 3 version goes into the profiled nmethods heap. The tier 4 version goes into the non-profiled nmethods heap. The split is useful because tier 3 code is short-lived, since it is replaced once tier 4 code exists. Keeping it apart from long-lived tier 4 code avoids fragmentation, makes sweeping cheaper, and keeps the optimized code more compact in memory, which helps instruction cache locality.