Video in progress

Strong Middle ⚙️ JVM and memory

What happens when the code cache fills up, and how do you detect it?

The JIT can no longer compile new methods: the log says "CodeCache is full. Compiler has been disabled", and new hot code stays in the interpreter. The application doesn't throw an error, but it slowly gets several times slower.

📖 Answer

The code cache is the off-heap area where the native code compiled by the JIT is stored. In Java 9+ it is split into three segments (non-method, profiled, non-profiled), and with tiered compilation the default total size is 240 MB.

This rarely happens, but when it does it is very misleading: CPU goes up, latency grows, and the heap and GC look normal. It usually shows up in very big monoliths with many dynamically generated classes (proxies, Groovy scripts, bytecode generation).

To check:

jcmd $PID Compiler.codecache
# or
jcmd $PID VM.native_memory summary | grep -A3 Code

You can also watch the Micrometer metric jvm_memory_used_bytes{id=~"CodeHeap.*"}.

The fixes:

  • increase it with -XX:ReservedCodeCacheSize=512m, the quickest and safest;
  • -XX:+UseCodeCacheFlushing is on by default; check that you haven't turned it off;
  • find the place that creates too many dynamic classes (for example, compiling a new script on every request).

I put the code cache metric on the dashboard next to the heap, so the problem is visible before it starts.