Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A long-running service fails with OutOfMemoryError: Metaspace after a few days, and another logs CodeCache is full. Compiler has been disabled. Explain each and how you would investigate.

OutOfMemoryError: Metaspace means the native memory that holds class metadata reached its limit, which almost always means classes are being generated or loaded again and again, by dynamic proxies, scripting engines or a class loader leak; we investigate with jcmd VM.metaspace and class loader statistics, and a heap dump shows what keeps the loaders alive. 'CodeCache is full. Compiler has been disabled' means the area that holds JIT-compiled machine code is full, so the JVM stops compiling and the service slowly gets slower; we check it with jcmd Compiler.codecache, raise ReservedCodeCacheSize if the application simply needs more, or find what generates so much code. Both should be monitored as metrics.

Why this question is asked

Both problems appear only after a service has run for a while, so they escape short tests and arrive as a 3 a.m. surprise. They are also confusing, because neither is about the heap that most memory tuning focuses on. Interviewers ask this pair together to see whether we know the non-heap areas of the JVM and have a method for investigating them. In this answer, we will recap what each area holds, look at the typical causes of a growing metaspace and how to find them, then do the same for the code cache, and end with the metrics that would have warned us.

1A Quick Recap: Metaspace and the Code Cache

Metaspace is native memory where the JVM keeps class metadata: each class's structure, fields, methods, bytecode and constant pool. It grows as classes are loaded, and memory is only given back when a class loader becomes unreachable and is collected together with all its classes. By default metaspace has no fixed limit, so an OutOfMemoryError: Metaspace means someone set -XX:MaxMetaspaceSize, which is good practice, and the application exceeded it.

The code cache is a separate native area for machine code produced by the JIT compilers, plus small pieces of code the JVM generates for itself. Its size is fixed at startup by -XX:ReservedCodeCacheSize, commonly 240 MB with tiered compilation (check your JVM's default with -XX:+PrintFlagsFinal). Since Java 9 it is split into segments for non-method code, profiled code and fully optimised code.

The two errors side by side
MetaspaceCode cache
HoldsClass metadata and bytecodeJIT-compiled machine code
SymptomOutOfMemoryError: MetaspaceWarning, compiler disabled, slower over time
Usual causeClasses generated or loaded repeatedlyVery large or generated code base
First commandjcmd <pid> VM.metaspacejcmd <pid> Compiler.codecache
Typical fixStop the leak or cache generated classesRaise ReservedCodeCacheSize, reduce generated code

2Why Metaspace Keeps Growing

A normal service loads its classes during startup and warm-up, then metaspace stays roughly flat. Steady growth over days means new classes keep being created. The usual sources are code that generates classes at runtime and never reuses them: creating a new CGLIB or Byte Buddy proxy class per call instead of caching it, compiling a Groovy or other script into a new class on every request, building a new JAXBContext or a new dynamic serializer per call in some libraries, or a templating or rules engine that compiles expressions without a cache. The other big source is a class loader leak, where old loaders, for example from redeploys or plugin reloads, are kept alive by a stray reference, so their classes can never be freed.

Java
// A leak in waiting: a new script class for every request
Object evaluate(String script, Map<String, Object> vars) {
GroovyShell shell = new GroovyShell(new Binding(vars));
return shell.evaluate(script); // compiles the script into a brand new class each time
}
// Fixed: compile each distinct script once and reuse the class
private final Map<String, Class<? extends Script>> compiled = new ConcurrentHashMap<>();

Notice that the broken version looks harmless; each call works, and the classes are small. But at 100 requests per second, that is 8.6 million new classes per day, each with its own metadata, and often each with its own class loader too.

3Investigating Metaspace

The first step is to confirm that the number of classes is growing. jcmd gives us the counts and sizes without restarting anything, and comparing two snapshots an hour apart shows the trend.

Shell
jcmd 48213 VM.metaspace # used and committed metaspace, by loader type
jcmd 48213 VM.classloader_stats # every loader: type, number of classes, bytes
# ClassLoader Classes ChunkSz
# groovy.lang.GroovyClassLoader$InnerLoader 1 3.1K (x 41,880 entries)
jcmd 48213 GC.class_histogram | head -20 # instance counts, including java.lang.Class
jcmd 48213 GC.heap_dump /tmp/heap.hprof # for the path to GC roots

In this example the class loader statistics show tens of thousands of tiny Groovy inner loaders, each with one class, which points directly at script compilation. When the statistics instead show several large loaders of the same type, such as web application loaders, we suspect a loader leak, and the heap dump answers why they are still alive: in Eclipse Memory Analyzer we pick one old loader and ask for the path to GC roots, which might end at a thread's ThreadLocal, a static cache or a JDBC driver registration. Running with -Xlog:class+load briefly also shows which classes are loaded continuously.

4When the Code Cache Fills Up

When the code cache is full, the JVM prints a warning such as 'CodeCache is full. Compiler has been disabled.' and suggests increasing ReservedCodeCacheSize. The application keeps running, but no new methods are compiled. Methods already compiled stay fast, but any code that becomes hot later, after a deployment of new features or a change in traffic, stays interpreted, which can be many times slower. So the symptom is a gradual, unexplained rise in CPU and latency, not a crash. Modern JVMs can also evict cold compiled code to make room, so the compiler may come back on, but a cache that keeps hitting its limit signals a real problem.

Causes are a very large application with lots of hot code, aggressive inlining, many generated classes that each get compiled, or a code cache size set too small by an old JVM option copied from somewhere.

5Investigating and Fixing the Code Cache

jcmd shows the size, usage and the high-water mark of each segment, and whether compilation is still enabled. If usage is close to the maximum and the code base is genuinely large, the fix is simply a bigger cache, for example 512 MB, which costs only native memory. If usage keeps climbing over days, we look for generated code, often the same sources as metaspace growth, since every generated class that gets hot is compiled too.

Shell
jcmd 48213 Compiler.codecache
# CodeHeap 'non-profiled nmethods': size=119168Kb used=118990Kb max_used=119168Kb free=178Kb
# CodeHeap 'profiled nmethods': size=119172Kb used=86012Kb ...
# ...
# compilation: disabled (not enough contiguous free space left)
java -XX:ReservedCodeCacheSize=512m -jar app.jar # more room for compiled code
jcmd 48213 Compiler.CodeHeap_Analytics # detailed breakdown of what is in it

Notice the line compilation: disabled. That single line explains a slow service. After raising the size, we watch that usage settles below the new limit rather than growing into it again.

6Monitoring Both as Metrics

Both problems are gradual, so metrics catch them long before an outage. With Micrometer in Spring Boot, jvm.memory.used and jvm.memory.max are published per memory pool, including Metaspace and the code cache segments (named CodeHeap with the segment name). jvm.classes.loaded and jvm.classes.unloaded show class churn. An alert when metaspace usage keeps rising for hours, or when any code heap passes 90 percent of its maximum, turns a future 3 a.m. outage into a daytime ticket.

Step throughInvestigating a non-heap memory problem
  1. Which area?
    YesMetaspace: class metadataNoCode cache: compiled code
  2. Metaspace: VM.classloader_stats over timemany tiny loaders or a few large leaked ones?
  3. Heap dump: path to GC roots from an old loaderwhat keeps it alive?
  4. Code cache: Compiler.codecachefull segment, compilation disabled?
  5. Fix the cause, then size the limitand alert on the trend

5 steps in order. Play them, or step through them one at a time.

7Follow-up questions

Should we just remove MaxMetaspaceSize so the error goes away?

No. Without a limit, a leak keeps consuming native memory until the container or the operating system kills the process, which is harder to diagnose than a clear OutOfMemoryError. A limit makes the failure explicit. The right response is to find what generates or retains the classes; then the limit can stay with comfortable headroom.

Can a full code cache be caused by a deployment rather than a leak?

Yes. A release that adds a large feature, a new library or different traffic patterns can make more code hot, and a cache sized just right for the old version overflows. In that case usage jumps after the deployment and then stays flat near the limit, and raising ReservedCodeCacheSize is the correct fix.

Why do metaspace and code cache problems often appear together?

Because they share a common cause. Code that generates new classes at runtime fills metaspace with their metadata, and when those classes become hot, the JIT compiles them, filling the code cache as well. Fixing the class generation often fixes both.

8Conclusion

In this answer, we saw that metaspace holds class metadata and is only freed when class loaders die, so steady growth means classes are generated or loaded repeatedly, through uncached proxies, scripts or class loader leaks; we investigated with VM.metaspace, class loader statistics and a heap dump. The code cache holds JIT-compiled code; when full, compilation stops and performance degrades quietly; we checked it with Compiler.codecache and raised ReservedCodeCacheSize or reduced generated code. Both are best caught early through per-pool memory and class count metrics.

What to say in the interviewAbout 90 seconds aloud

Open with

These are two different non-heap areas. Metaspace holds class metadata, the class structures, methods and bytecode, and it is only freed when a class loader becomes unreachable. Metaspace is unlimited by default, so this error means a MaxMetaspaceSize was set and we exceeded it.

Then, if they want more

A service that dies after a few days is creating classes continuously: dynamic proxies generated per call instead of cached, scripts compiled on every request, or a class loader leak where old loaders from redeploys stay referenced. I would run jcmd VM.metaspace and VM.classloader_stats a few times to see what grows.

Thousands of tiny loaders with one class each point at generation, while several large loaders of the same type point at a leak, and then a heap dump and the path to GC roots from an old loader shows what keeps it alive. The code cache holds machine code from the JIT.

When it is full the JVM disables the compiler, so the service keeps running but newly hot code stays interpreted and gets slower over time. I would check jcmd Compiler.codecache for segment usage and whether compilation is disabled.

If the application is just large, I raise ReservedCodeCacheSize, for example to 512 megabytes; if usage keeps climbing, I look for generated code, which often is the same cause as the metaspace growth. And I would monitor both as metrics, metaspace and code heap usage and loaded classes, with alerts on trends.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A long-running service fails with OutOfMemoryError: Metaspace after a few days, and...": https://scrivio-interview-library.netlify.app/java/jvm-architecture/5b5e45fd80/