Video in progress

A service generates many Groovy scripts, dynamic proxies and lambdas at runtime, and metaspace grows by the hour. How do you analyze it and how do you change the design?

First I find which classloaders and which classes are multiplying with VM.classloader_stats and VM.metaspace. The cause is usually a new class being generated on every request; the fix is caching the compilation result and limiting the number of classloaders.

📖 Answer

Metaspace is native memory for class metadata. A class is freed only when the classloader that loaded it is collected. With dynamic generation there are two situations: the classes multiply but do get collected (which is just a CPU and GC cost), or they don't get collected (a leak).

Diagnostics:

jcmd <pid> VM.metaspace             # overall state, fragmentation
jcmd <pid> VM.classloader_stats     # per loader: number of classes, size
jcmd <pid> GC.class_histogram | grep -i -E 'groovy|proxy|lambda'
-Xlog:class+load=info,class+unload=info   # the stream of loads/unloads

Typical findings:

  • Groovy. GroovyShell.evaluate(script) creates a new class on every call, and often a new classloader, even if the script text is the same.
  • Proxies. Proxy.newProxyInstance caches by the set of interfaces, but if a new classloader is passed each time, the cache doesn't work. With CGLIB/ByteBuddy too, a new naming strategy or loader on every call means a new class.
  • Lambdas. Usually not a problem: one hidden class per lambda expression. But using LambdaMetafactory by hand, on every call, is a different story.

Design changes:

  • compile scripts once and cache them by the text's hash (a Map<String, Class<? extends Script>>, or GroovyClassLoader + parseClass), with a size limit;
  • a separate classloader per tenant or per script version, but close the old one explicitly and cut the references;
  • move generation to startup time;
  • set -XX:MaxMetaspaceSize: if there is a leak, you get a clear OutOfMemoryError: Metaspace instead of the container being OOMKilled.

I confirm the result with the class+unload log and the metaspace graph: the loading and unloading of new classes should come into balance.