Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

You are designing a plugin system where third-party jars register handlers. One proposal scans all classes with reflection at startup; another uses ServiceLoader. Compare them for a platform used by many teams.

For a platform used by many teams, ServiceLoader is the better foundation. Each plugin registers its handlers explicitly in META-INF/services or with provides in module-info, so discovery is fast, only intended classes are exposed, it works with the module system and native images, and the service interface becomes a stable, versioned contract. Class-path scanning is convenient for authors but slow on large class paths, picks up classes nobody meant to expose, and depends on reflective access that strong encapsulation can block.

Why this question is asked

Plugin systems live for a long time. Once dozens of teams ship handlers against our platform, the way handlers are found becomes part of the contract we cannot easily change. Interviewers ask this design question to see whether we can look past convenience on day one and consider startup cost, security, the module system, native images and versioning over years. In this answer, we will recap both approaches, look at what scanning really costs, build the ServiceLoader version, compare them side by side, and then isolate plugins in their own class loaders.

1A Quick Recap of the Two Approaches

In the scanning approach, the platform looks through every class on the class path at startup, loads or reads each one, and keeps the ones that implement Handler or carry a @Handler annotation. Plugin authors only write the class; nothing else is needed. Spring's component scanning is the best-known example.

In the ServiceLoader approach, which has been in the JDK since Java 6, the platform defines a service interface, and each plugin jar declares which classes implement it. On the class path that declaration is a text file named after the interface inside META-INF/services. In a modular jar it is a provides clause in module-info.java. At run time, ServiceLoader.load(Handler.class) reads those declarations and instantiates only the listed classes.

2What Class-Path Scanning Really Costs

Scanning sounds free, but its cost grows with everything on the class path, not with the number of plugins. A typical service has 150 to 300 jars and tens of thousands of classes. The scanner must open every jar and read every class file, at least its header and annotations, to decide whether it matters. On a large application this adds seconds to startup, and the cost is paid again on every start of every instance.

It also finds too much. Any class that happens to implement Handler is picked up, including test helpers, internal base classes and handlers a team was still developing, so the plugin's real surface is whatever the scan happens to find. And to instantiate classes the plugin author did not expose, the scanner needs reflective access. In a modular application that requires the plugin to open its packages, and strong encapsulation will refuse if it does not. Finally, GraalVM native images cannot scan a class path at run time, because there is no class path, so every scanned class must be listed ahead of time anyway.

3Building the ServiceLoader Version

We publish a small API jar with the service interface. Each plugin jar implements it and registers its classes.

Java
// platform-api.jar
package com.acme.platform.spi;
public interface Handler {
String eventType(); // for example "order.created"
void handle(Event e);
default int apiVersion() { return 1; } // lets the platform evolve the contract
}
// plugin jar on the class path: file META-INF/services/com.acme.platform.spi.Handler
com.acme.shipping.OrderCreatedHandler
com.acme.shipping.OrderCancelledHandler
// or, for a modular plugin jar, module-info.java
module com.acme.shipping {
requires com.acme.platform.api;
provides com.acme.platform.spi.Handler
with com.acme.shipping.OrderCreatedHandler, com.acme.shipping.OrderCancelledHandler;
}

The platform then loads handlers lazily. ServiceLoader.stream() returns providers whose type we can inspect before creating an instance, so a misbehaving plugin can be skipped without running its constructor.

4Loading the Handlers at Startup

Here is the platform side, with the result for two plugin jars on the class path.

Java
Map<String, Handler> byEvent = new HashMap<>();
ServiceLoader.load(Handler.class).stream()
.forEach(p -> {
Handler h = p.get(); // instantiates only listed classes
Handler old = byEvent.putIfAbsent(h.eventType(), h);
if (old != null) throw new IllegalStateException("two handlers for " + h.eventType());
});
System.out.println(byEvent.keySet()); // [order.created, order.cancelled, invoice.paid]
Step throughServiceLoader discovery
PlatformServiceLoaderPlugin jar
load(Handler.class)
read META-INF/services or provides
two class names
lazy stream of providers
provider.get()
instantiate OrderCreatedHandler
Handler instance

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

Notice that discovery reads only a few small text files or module descriptors, so it takes milliseconds regardless of how large the class path is. Only registered classes are instantiated, the module system checks the provides clause at startup and does not require the plugin to open anything, and GraalVM's native image build includes registered services when it sees them in META-INF/services or module descriptors (check your GraalVM version for the exact rules).

5Comparing Them for a Platform Used by Many Teams

Put side by side, the deciding factors are the ones that matter over years rather than on the first day.

Scanning versus ServiceLoader
ConcernClass-path scanningServiceLoader
Startup costGrows with every class on the class pathReads a few registration files
What is exposedWhatever the scan findsOnly classes the author registered
Module systemNeeds opens for reflective accessSupported through provides and uses
Native imagesNeeds every class listed ahead of timeRegistered services are included
ContractImplicit, by naming or annotationExplicit, versioned service interface
Author effortNoneOne registration line, can be generated

The main cost of ServiceLoader is the registration step, which authors can forget. We remove that friction with tooling: an annotation processor such as Google's AutoService generates the META-INF/services file from an @AutoService(Handler.class) annotation, and a test in the plugin template fails if a Handler class is not registered. And because the interface lives in a versioned API jar, we can add default methods, deprecate old ones and check apiVersion() at load time, giving teams a contract they can rely on.

6Follow-up questions

How would you load plugins with isolated class loaders?

I would give each plugin jar its own URLClassLoader whose parent is the loader that holds the platform API, not the application loader, so plugins share the Handler interface but not each other's dependencies. Then I call ServiceLoader.load(Handler.class, pluginLoader) for each one. Two plugins can then use different versions of the same library. For modular plugins, the same idea is a ModuleLayer per plugin created with ModuleLayer.defineModulesWithOneLoader. Closing the loader and dropping all references lets a plugin be unloaded.

Is Spring's component scanning a bad idea, then?

Not inside one application, where the team owns all the classes and the scan is limited to its own base packages. The problems appear when scanning is the contract between a platform and many independent teams' jars. Spring Boot itself finds auto-configuration classes through an explicit registration file in META-INF/spring, not by scanning other teams' jars.

What if a plugin's constructor throws?

ServiceLoader wraps it in a ServiceConfigurationError when we call get() or iterate. The platform should catch that per provider, log which plugin failed, and decide whether to continue without it or fail startup, rather than letting one broken plugin stop all the others.

7Conclusion

In this answer, we compared class-path scanning with ServiceLoader for a plugin platform. Scanning costs startup time that grows with the whole class path, exposes classes the author did not intend, needs reflective access that strong encapsulation can block, and does not fit native images. ServiceLoader uses explicit registration in META-INF/services or a provides clause, which is fast, works with modules and native images, and gives a stable, versioned contract, and we can isolate plugins with a class loader or module layer each.

What to say in the interviewAbout 80 seconds aloud

Open with

For a platform used by many teams I'd choose ServiceLoader. Scanning means opening every jar and reading every class at startup, so the cost grows with the whole class path, which for a big service can be seconds on every start.

Then, if they want more

It also finds anything that implements the interface, including classes the author never meant to expose, and it needs reflective access, which strong encapsulation blocks unless the plugin opens its packages. Native images can't scan at run time at all. With ServiceLoader, I publish a small versioned API jar with the Handler interface.

Each plugin registers its implementations, either in a META-INF/services file named after the interface or with a provides clause in module-info. Discovery just reads those registrations, so it takes milliseconds, only registered classes get instantiated, it works with the module system, and native image includes registered services.

The interface is the explicit contract: I can add default methods and an API version check. The cost is that authors must register, so I'd generate it with AutoService and add a template test.

If plugins need different library versions, I'd load each in its own class loader, parented to the API loader, and call ServiceLoader.load with that loader, or use a module layer per plugin.

About this answer

Last updated
12 November 2026
Versions it names
Java 6
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 "You are designing a plugin system where third-party jars register handlers. One proposal...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/7f9a15d62e/