Java / Java 17 Garbage Collection Interview Questions
Explain how class unloading interacts with garbage collection and Metaspace?
Class metadata - bytecode, constant pools, method and field descriptors - lives in Metaspace, and a class can only be unloaded, freeing its slice of Metaspace, once the ClassLoader that defined it becomes completely unreachable: no live instances of any class it loaded, and no remaining references to the loader itself.
Determining that a classloader is unreachable is itself a garbage collection concern - it requires tracing reachability the same way ordinary object graphs are traced. G1 can identify unreachable classloaders during its concurrent marking cycle when -XX:+ClassUnloadingWithConcurrentMark is enabled (the default), letting Metaspace be reclaimed without waiting for a full GC; without concurrent-mark-based unloading, class unloading only happens during a full GC.
The most common real-world leak pattern is an application server or framework that repeatedly creates short-lived custom classloaders (hot redeploys, dynamic proxy generation, plugin systems) where something outside the loader - a static field on a class loaded by the parent loader, a thread-local, a still-registered JDBC driver or shutdown hook - keeps a reference alive. That single stray reference is enough to keep the entire classloader, and every class and its Metaspace footprint, from ever being unloaded, which is why repeated redeploys of this kind are the classic cause of a slowly growing, eventually fatal OutOfMemoryError: Metaspace.
More Related questions...