Java doesn't provide an explicit API to unload an individual class on demand. Instead, a class can only become eligible for unloading indirectly, as a side effect of its defining class loader being garbage collected, which itself requires that nothing references the class loader or any class or instance it loaded.
Key Points: • A class becomes unloadable only when its class loader is unreachable, no instances of any class it loaded still exist, and the Class objects themselves aren't referenced elsewhere. • Classes loaded by the bootstrap, platform, or application class loaders are effectively never unloaded, since those loaders live for the JVM's entire lifetime. • Custom class loaders, used by application servers, plugin systems, or hot-reload frameworks, are the practical way to get class unloading, since discarding the loader after use allows its classes to be collected. • A common leak pattern in such environments is a static field or thread-local referencing a class or instance from a loader that should have been discarded, which pins the entire loader, and every class it loaded, in memory. • Metaspace, where class metadata lives, is reclaimed by garbage collection just like heap space once a class becomes unreachable this way.
Example: An application server that redeploys a web application without restarting the JVM relies on discarding the old deployment's class loader; if a background thread or static reference from another part of the system still holds onto a class from the old deployment, that entire class loader, and all its classes, leaks memory across redeployments.
Interview Tip: A concise interview answer is:
"You can't unload a single class directly in Java — it only happens indirectly when the class loader that loaded it becomes unreachable and gets garbage collected. This matters most in app servers that support hot redeployment, where a lingering reference to an old class or instance can pin the whole class loader in memory, a classic classloader leak."