Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a minimal class loader that loads plugin classes from a directory of .class files, and explain which method you override and why. The host application must be able to use plugins through a PluginApi interface.

We extend ClassLoader and override findClass: it turns the class name into a file path under the plugin directory, reads the bytes and calls defineClass, throwing ClassNotFoundException when the file is missing. Because loadClass still delegates to the parent first, the PluginApi interface comes from the host's class path, so plugin classes implement the host's own PluginApi and can be cast to it. For jars we would use URLClassLoader, and we close it and drop every reference when a plugin is removed.

Why this question is asked

Plugin systems are one of the few places where application developers still write class loaders, and they are a good interview exercise because a small amount of code touches several deep rules: delegation, class identity, thread safety and unloading. Getting one detail wrong produces errors that are hard to explain, such as a plugin object that cannot be cast to the interface it clearly implements. In this answer, we will recap the pieces we need, write the loader, wire it into a host that uses PluginApi, see the bug that appears when the interface is in the wrong place, and then cover thread safety, jars and unloading.

1A Quick Recap of What We Need

A class loader finds the bytes of a class and asks the JVM to define it with defineClass. The base class java.lang.ClassLoader already implements loadClass, which checks the loader's cache, asks the parent loader, and only then calls findClass. findClass is the method left for us to override: it runs only for classes the parent could not find.

In our design there are two kinds of classes. PluginApi is the contract, an interface the host compiles against and calls. The plugin classes, such as com.acme.plugins.Greeter, implement PluginApi and live as .class files in a directory such as plugins/greeter/com/acme/plugins/Greeter.class. The host never sees those classes at compile time; it learns their names from configuration and loads them at run time.

2Writing the Loader

Here is a minimal loader for a directory of .class files.

Java
public final class DirectoryPluginLoader extends ClassLoader {
static {
ClassLoader.registerAsParallelCapable(); // lock per class name, not per loader
}
private final Path root;
public DirectoryPluginLoader(Path root, ClassLoader parent) {
super("plugin:" + root.getFileName(), parent); // a name shows up in error messages
this.root = root;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Path file = root.resolve(name.replace('.', '/') + ".class");
if (!Files.isRegularFile(file)) {
throw new ClassNotFoundException(name);
}
try {
byte[] bytes = Files.readAllBytes(file);
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
}
}

Notice that we override findClass and nothing else. The reason is that loadClass already does the cache check, the delegation and the locking. By plugging in at findClass, our directory becomes the last place searched, after the JDK and the host's class path, which is exactly what we want for a plugin.

3Using Plugins From the Host

The host creates one loader per plugin, loads the class by name, and works with it only through PluginApi.

Java
public interface PluginApi { // on the host's class path
String name();
String handle(String input);
}
ClassLoader host = PluginApi.class.getClassLoader();
DirectoryPluginLoader loader = new DirectoryPluginLoader(Path.of("plugins/greeter"), host);
Class<? extends PluginApi> type = Class.forName("com.acme.plugins.Greeter", true, loader)
.asSubclass(PluginApi.class);
PluginApi plugin = type.getDeclaredConstructor().newInstance();
System.out.println(plugin.name()); // greeter
System.out.println(plugin.handle("Ana")); // Hello, Ana
System.out.println(type.getClassLoader()); // DirectoryPluginLoader named plugin:greeter
System.out.println(PluginApi.class.getClassLoader()); // the application loader
Step throughLoading Greeter through the plugin loader
HostPlugin loaderApp loader
forName("com.acme.plugins.Greeter")
loadClass(Greeter): parent first
not on the class path
findClass: read Greeter.class, defineClass
Greeter needs PluginApi: parent first
PluginApi (the host's copy)
Greeter, implements the host's PluginApi

7 messages in order. Play them, or step through them one at a time.

When the JVM defines Greeter, it sees that Greeter implements PluginApi and asks Greeter's loader for PluginApi. Our loader delegates to its parent, the host's application loader, which already has PluginApi. So Greeter implements the very same PluginApi type the host compiled against, and the cast inside asSubclass succeeds.

4The Bug When PluginApi Is in the Wrong Place

A common mistake is to copy PluginApi.class into the plugin directory as well, for example because the plugin's build output includes it. That alone is harmless, because delegation finds the host's copy first. The real bug appears when the plugin classes are also on the host's class path, or when someone writes the loader child first by overriding loadClass and searching the directory before the parent.

Java
// child-first loader that also finds com/acme/api/PluginApi.class in the plugin directory
PluginApi p = (PluginApi) type.getDeclaredConstructor().newInstance();
// java.lang.ClassCastException: class com.acme.plugins.Greeter cannot be cast to class
// com.acme.api.PluginApi (Greeter is in unnamed module of loader 'plugin:greeter';
// PluginApi is in unnamed module of loader 'app')

Greeter now implements the plugin loader's own copy of PluginApi, which is a different type from the host's PluginApi even though the names match. The fix is to keep the contract in exactly one place, the host, and always let it come from the parent. And the opposite mistake matters too: if Greeter itself is on the host's class path, the parent finds it first, the plugin loader is never used, and the plugin can never be unloaded.

5Thread Safety and Jars

The static block calling ClassLoader.registerAsParallelCapable() tells the JDK that this loader may be used by many threads at once. Without it, loadClass locks the whole loader object, so two threads loading two different plugin classes wait for each other, and in unlucky cases with cross-loader calls this can even deadlock. With it, getClassLoadingLock returns a lock per class name. The call must be made from the subclass's static initializer and only works if the superclass is parallel capable too, which ClassLoader is.

If plugins ship as jars rather than loose class files, we do not need our own findClass at all. URLClassLoader already reads classes and resources from jar files and directories, and it is itself parallel capable.

Java
URLClassLoader jarLoader = new URLClassLoader("plugin:billing",
new URL[] { Path.of("plugins/billing.jar").toUri().toURL() }, host);

6Removing a Plugin Cleanly

A class can only be unloaded together with its loader, and only when nothing reachable refers to the loader, its classes or their objects. So removing a plugin means two things. First, for a URLClassLoader, call close(), which closes the open jar files; on Windows an unclosed jar cannot even be deleted, and everywhere it keeps file handles open. Second, drop every reference: the PluginApi instance, the Class object, and the loader itself. After that, a garbage collection that unloads classes can free the plugin's classes from metaspace.

The hard part is references we did not create on purpose. A thread the plugin started and never stopped, a ThreadLocal value it left on a host thread, a listener it registered in a static registry of the host, or a JDBC driver it registered in DriverManager all keep the loader alive. A good host gives plugins a lifecycle method such as stop() and cleans up its own registries when the plugin is removed.

7Follow-up questions

How would you let each plugin use its own version of a JSON library?

Give each plugin its own loader whose search path includes the plugin's own copy of the library, and make sure the library is not on the host's class path, so delegation cannot find a host copy first. If the host must also use that library, either keep it out of the API types and accept two versions in different loaders, or make the plugin loader child first for the library's packages only while still delegating java.* and the PluginApi package to the parent. The rule is that types appearing in PluginApi must be shared, and everything else can be private to the plugin.

What would stop the plugin loader from being garbage collected?

Any strong reference path from a GC root to the loader, one of its classes, or an instance of one of its classes. Typical culprits are threads started by the plugin, ThreadLocal values on long-lived host threads, plugin objects kept in host caches or listener lists, JDBC drivers registered in DriverManager, shutdown hooks, and JMX MBeans. A heap dump with a path to GC roots for the old loader shows which one it is.

8Conclusion

In this answer, we wrote a directory plugin loader by extending ClassLoader and overriding findClass, which maps the name to a .class file, reads the bytes and calls defineClass. Keeping PluginApi on the host's class path means delegation gives every plugin the host's copy, so plugin objects can be cast to it; putting it in two places produces a cast failure between two types with the same name. We registered the loader as parallel capable, saw that URLClassLoader handles jars, and that removing a plugin means closing the loader and dropping every reference so it can be collected.

What to say in the interviewAbout 90 seconds aloud

Open with

I would extend ClassLoader and override findClass, not loadClass. loadClass already does the cache check, the delegation to the parent and the locking, so overriding findClass makes my plugin directory the last place searched, which keeps JDK and host classes coming from the parent.

Then, if they want more

In findClass I replace dots with slashes, add .class, resolve that against the plugin directory, read the bytes and call defineClass with name, bytes, zero and length. If the file does not exist I throw ClassNotFoundException. The host keeps the PluginApi interface on its own class path.

When the JVM defines a plugin class that implements PluginApi, it asks the plugin loader for PluginApi, the loader delegates to the host loader, and so the plugin implements the host's exact type and I can cast instances to it.

If PluginApi were loaded by the plugin loader too, I would get a ClassCastException between two types with the same name. I would add a static block that calls registerAsParallelCapable so concurrent loads lock per class name. For jars I would just use URLClassLoader.

When a plugin is removed, I close the URLClassLoader to release the jar files and drop all references to the loader, its classes and its instances, and I make sure the plugin stopped its threads, so the loader can be garbage collected and its metaspace freed.

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 "Write a minimal class loader that loads plugin classes from a directory of .class files...": https://scrivio-interview-library.netlify.app/java/class-loading/1a5f5ecd28/