Video in progress
You are designing a system that loads and updates plugins at runtime. How do you prevent classloader leaks?
Each plugin is loaded in its own classloader, and when it is removed no strong reference to it may remain. The main enemies are static registries, ThreadLocals, threads, JDBC drivers and cached reflection objects.
📖 Answer
A classloader is collected only when nothing references any of the classes it loaded or any of their objects. A single remaining reference keeps the entire plugin in memory: all its classes, its static fields and its space in metaspace. This repeats with every update, and in the end you get OutOfMemoryError: Metaspace.
The sources of leaks and the rules:
- Static registries in the host. If a plugin adds a listener to the host's
EventBus, the host holds on to the plugin class.unregistershould be mandatory for every registration, and better still, tied to the plugin context. - Threads. A thread the plugin opened holds the plugin through its context classloader. The executor for a plugin is provided by the host and closed on unload.
- ThreadLocal. If a plugin value stays on the host's pool threads, that is a leak.
- JDBC
DriverManager,java.beans.Introspector, logging libraries. These keep global caches.
At the design level:
interface Plugin extends AutoCloseable {
void start(PluginContext ctx); // resources only through ctx
}
// unload: plugin.close(); ctx.closeAll(); loader.close(); null out the references
To verify, I load and unload a plugin 100 times in a test, then count the plugin classloader instances with jcmd <pid> VM.classloader_stats or in a heap dump. If more than 1 remains, Path to GC Roots shows the culprit.
Sometimes the right decision is to give up hot reload: run the plugin in a separate process, or recreate the container. That guarantees isolation and removes the classloader complexity.
Sign up to mark studied questions and save your progress.