Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Name three ways an application can keep creating new classes at run time and grow metaspace without any redeploys, and how you would notice it.

Three common ways are generating a new proxy or bytecode subclass per request instead of once per type, compiling scripts or expressions at run time in a fresh class loader for every evaluation, and compiling XSLT templates or generated serializers on every call instead of caching them. We notice it as metaspace that grows steadily under constant traffic: the MU column of jstat -gc, the Metaspace pool in Micrometer's jvm.memory.used, jcmd VM.metaspace, or a loaded-class count that keeps rising. -Xlog:class+load then shows which classes are being defined over and over.

Why this question is asked

Metaspace leaks are usually explained with redeploys in an application server, but plenty of services that are never redeployed run out of metaspace too. The cause is code that keeps defining new classes while the service runs, often deep inside a library call that looks innocent. Interviewers ask this to see whether we know which APIs generate classes and how to spot the pattern from metrics. In this answer, we will recap what metaspace holds, go through three common sources of run-time class generation with the broken and fixed code, and then see how to notice and confirm the problem.

1A Quick Recap of Metaspace

Metaspace is the native memory area where the JVM keeps class metadata: bytecode, method and field descriptions, and constant pools. Every class defined at run time takes space there, typically a few kilobytes for a small generated class and much more for a large one. Metaspace is not part of the heap, and by default it has no upper limit other than the machine's memory, unless we set -XX:MaxMetaspaceSize. When the limit is reached, the JVM throws OutOfMemoryError: Metaspace; in a container without a limit, the process can simply be killed for using too much memory.

Classes are freed only when their defining class loader becomes unreachable. So run-time class generation is fine if each generated class is created once and reused, or if the classes and their loader are thrown away together. It becomes a leak when new classes keep appearing and something keeps them alive.

2Source 1: Proxies and Generated Subclasses per Request

Libraries such as ByteBuddy and CGLIB create subclasses at run time, and the JDK's java.lang.reflect.Proxy creates proxy classes for interfaces. These are meant to be created once per type. The bug is building a new class for every call.

Java
// Broken: a brand-new class for every request
Object auditing(Object target) {
return new ByteBuddy()
.subclass(target.getClass())
.method(any()).intercept(MethodDelegation.to(new AuditInterceptor()))
.make()
.load(target.getClass().getClassLoader()) // defines another class each time
.getLoaded()
.getDeclaredConstructor().newInstance();
}
// Fixed: one generated class per target type, cached
private final ClassValue<Class<?>> auditTypes = new ClassValue<>() {
@Override protected Class<?> computeValue(Class<?> type) {
return new ByteBuddy().subclass(type)
.method(any()).intercept(MethodDelegation.to(AuditInterceptor.class))
.make().load(type.getClassLoader()).getLoaded();
}
};

In the broken version, a service handling 200 requests per second defines 200 classes per second, around 17 million a day. Each lands in the target's class loader, often the application loader, which never unloads, so metaspace only grows. The fix generates one class per target type, caches it in a ClassValue (a per-class cache that does not keep loaders alive by itself), and creates cheap instances of it. JDK Proxy caches its proxy classes per loader and interface list, so repeated Proxy.newProxyInstance calls are usually safe, but CGLIB and ByteBuddy only cache when we ask them to, and with callbacks that differ per call the cache can miss every time.

3Source 2: Scripts and Expressions Compiled per Evaluation

Scripting engines such as Groovy, and some expression engines and rule engines, compile each script into one or more JVM classes. A new engine or shell per evaluation means a new class loader and new classes every time.

Java
// Broken: a new GroovyShell, a new loader and new classes for each evaluation
Object eval(String script, Map<String, Object> vars) {
return new GroovyShell(new Binding(vars)).evaluate(script);
}
// Fixed: compile each distinct script once and reuse the compiled class
private final GroovyShell shell = new GroovyShell();
private final Map<String, Class<? extends Script>> compiled = new ConcurrentHashMap<>();
Object eval(String script, Map<String, Object> vars) {
Class<? extends Script> type = compiled.computeIfAbsent(script, s -> shell.parse(s).getClass());
Script s = InvokerHelper.createScript(type, new Binding(vars));
return s.run();
}

Notice that in the broken version the old loaders could in principle be collected, but in practice they are often kept alive by internal caches or by the scripts' own results, and even when they are collected, constant class churn costs CPU and GC time. The fix keys a cache by script text, so a thousand evaluations of the same rule create one class. If the scripts themselves are unbounded, for example generated from user input, the cache must be bounded and the compiled classes grouped in loaders that are discarded together.

4Source 3: XSLT Templates and Generated Serializers per Call

The JDK's built-in XSLT processor compiles each stylesheet into Java classes, called translets. Calling TransformerFactory.newTransformer(stylesheet) on every request compiles the stylesheet again each time. Some serialization and mapping libraries similarly generate optimized classes per type or per context, such as a JAXBContext or a mapper created per call.

Java
// Broken: compiles the stylesheet into new classes on every call
Transformer t = TransformerFactory.newInstance().newTransformer(new StreamSource(xslFile));
// Fixed: compile once into thread-safe Templates, create cheap Transformers from it
private static final Templates INVOICE = compile("invoice.xsl"); // at start-up
Transformer t = INVOICE.newTransformer(); // per call, no new classes
Run-time class generation: broken and fixed
SourceBroken patternFix
ByteBuddy, CGLIB subclassesmake().load() per requestone class per type in a ClassValue cache
Groovy and script enginesnew GroovyShell per evaluationparse once per script, reuse the class
XSLTnewTransformer(source) per callcompile Templates once
Serializers, JAXBnew context or mapper per callone shared, thread-safe instance

The Templates object is the compiled, thread-safe form of the stylesheet, and newTransformer on it only creates a light object. The same rule applies to any expensive context object: create it once, at start-up or lazily, and share it.

5Noticing It and Finding the Source

The signature is metaspace that grows steadily and does not drop after GCs, while traffic stays constant and nobody deploys. jstat gives a quick view: the MU column of jstat -gc is metaspace used in kilobytes. In production, Micrometer exposes it as jvm.memory.used with the id tag Metaspace, and the JMX ClassLoadingMXBean exposes the loaded-class count, which in a healthy service levels off a few minutes after start.

Shell
$ jstat -gc 4242 60s
MC MU ...
98304.0 95102.3 // minute 1
131072.0 127410.9 // minute 2
163840.0 159877.1 // minute 3: about 32 MB a minute, under steady traffic
$ jcmd 4242 VM.metaspace // totals and usage per loader type
$ java -Xlog:class+load=info -jar app.jar | grep -c ByteBuddy // generated classes defined so far

Once we know metaspace is growing, -Xlog:class+load prints every class as it is defined, with its name and source. Generated classes have recognisable names, such as names containing $ByteBuddy$, $$EnhancerByCGLIB$$, jdk.proxy, Script followed by a number, or translet class names, and seeing the same kind of name appear thousands of times points straight at the code that creates them.

6Follow-up questions

Why does a growing loaded-class count in JMX usually point to this problem?

In a normal service, almost all classes are loaded during start-up and the first minutes of traffic, after which the count of currently loaded classes stays flat. A count that keeps rising under steady traffic means classes are still being defined, and if the unloaded-class counter stays near zero, they are also never freed. That is exactly the pattern of run-time class generation without caching, so the loaded-class count is often the earliest and clearest signal, before metaspace becomes large enough to alert on.

Should we just set MaxMetaspaceSize?

Setting a limit is good practice, because it turns silent native memory growth into a clear OutOfMemoryError: Metaspace with a stack trace, and protects the container from being killed. But it does not fix anything: the generation continues and the limit is reached later. The fix is caching the generated classes.

7Conclusion

In this answer, we saw three ways a service can keep defining classes without any redeploy: generating proxies or subclasses per request with ByteBuddy, CGLIB or similar tools, compiling scripts or expressions in a new loader for every evaluation, and compiling XSLT stylesheets or generated serializers on every call. Each is fixed by creating the generated class or compiled object once and reusing it. We notice the problem as steadily rising metaspace in jstat's MU column, Micrometer's Metaspace pool or jcmd VM.metaspace, and as a loaded-class count that never levels off, and -Xlog:class+load shows which classes are being defined again and again.

What to say in the interviewAbout 90 seconds aloud

Open with

Metaspace holds class metadata, so it grows whenever the application keeps defining new classes, and classes are only freed with their loader. Three common ways this happens without any redeploy: first, generating proxies or subclasses at run time per request instead of once per type, for example calling ByteBuddy or CGLIB to make and load a new subclass on every call.

Then, if they want more

JDK Proxy caches per interface set, but the bytecode libraries only cache if you ask them to. Second, compiling scripts at run time, like creating a new GroovyShell or expression engine for every evaluation, which compiles the script into new classes in a new loader each time.

Third, compiling XSLT stylesheets or generated serializers per call, for example TransformerFactory.newTransformer with the stylesheet on each request, where the right thing is to compile Templates once. The fix in each case is to cache the generated class or compiled object and reuse it.

I would notice it as metaspace that rises steadily under constant traffic and never drops after GC: the MU column in jstat -gc, the Metaspace pool in Micrometer's jvm.memory.used, or jcmd VM.metaspace. An even earlier sign is the loaded class count in JMX, which should level off after start-up.

To find the source I turn on -Xlog:class+load and look for generated class names that appear thousands of times.

About this answer

Last updated
12 November 2026
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 "Name three ways an application can keep creating new classes at run time and grow...": https://scrivio-interview-library.netlify.app/java/class-loading/baf6b2c5db/