Lesson · Modules & Service Loading
Service Loading (SPI)
10 min readService Loading (SPI)
An SPI is an interface you publish, implementations someone else ships, and wiring that nobody compiles. ServiceLoader is the mechanism: a provider list that lives in the deployment, discovered lazily and instantiated on demand. This lesson covers both forms of that list, the provider contract, and the errors that tell you the packaging is wrong.
The wiring nobody wants to compile
An application needs an implementation it cannot name at compile time: the database driver for whatever database is deployed, the codec a plugin ships, the logging backend on the class path. The direct approach fails, because a compile-time reference to a class that may not be present is a dependency you cannot take.
The two obvious workarounds are worse than the problem. A class name in a properties file plus Class.forName moves the failure to a runtime string that no build checks. A switch over every implementation couples the application to each provider it will ever see, including ones that do not exist yet.
Codec codec = new FastCodec(); // the build now needs fast-codec.jar Codec other = new SlowCodec(); // and every future codec, forever String name = props.getProperty("codec"); // no compile-time check at all Codec dynamic = (Codec) Class.forName(name).getConstructor().newInstance();
- The service: one interface or abstract class that callers compile against, published as the extension point.
- The providers: implementations that someone else ships, in jars you never compile against and possibly never see.
- The wiring: an entry in the provider's own jar or module descriptor, read at run time by
ServiceLoaderinstead of by the compiler.
Compile against the interface; let the deployment pick the implementation. That sentence is the pattern, and the rest of this lesson is the mechanism that makes it work.
How ServiceLoader finds providers
ServiceLoader.load(Codec.class) returns a loader object, not instances. Locating providers begins when you iterate, and providers come from one of two places depending on how they are deployed.
On the class path, a provider jar carries a provider-configuration file under META-INF/services/, named after the fully qualified service type. The file lists fully qualified provider class names, one per line, encoded in UTF-8, with # starting a comment; surrounding spaces, tabs and blank lines are ignored, and a name that appears twice is used once.
In a module, the file is not needed. The provider module declares provides com.acme.Codec with com.acme.mod.CodecImpl; and the consumer declares uses com.acme.Codec;. That pair is also what the launcher uses to decide which provider modules belong in the graph, which is why a modularised application finds providers the class path never announced.
# META-INF/services/com.acme.Codec com.acme.fast.FastCodec # one fully qualified name per line com.acme.fast.SlowCodec # names are matched, not ranked com.acme.fast.FastCodec # listed twice: served once
| Class path provider | Module provider | |
|---|---|---|
| how it is declared | META-INF/services/(service name), one class name per line | provides (service) with (implementation); |
| what the consumer declares | nothing | uses (service); |
| when the declaration is read | while the loader iterates | when the loader is created: the caller's module must declare uses |
| duplicates | a name listed twice is served once | a provider also named in a services file is ignored |
- `load(Class)` uses the calling thread's context class loader. That one line of mechanism matters in practice: a container sets the context loader so a lookup can see the container's jars, and a loader that always reached for its own class loader would miss them.
- `load(Class, ClassLoader)` names the loader explicitly, and
load(ModuleLayer, Class)(Java 9 and later) searches named modules only. - Ordering is configuration order, not a ranking. The loader follows how the class loader finds configuration files and, in modules, the order the descriptor lists providers; the ordering of modules in a layer is explicitly undefined, so a first provider is arbitrary unless you filter for what you want.
The platform will not rank providers for you. If one implementation must win, write the rule: inspect each provider and choose, or select explicitly from the provider stream.
Discovery map · two sources, one lookup, one cache
structure only; the instantiation order is the play area's job
Locating and instantiating are two steps. Reading configuration and loading the class happens on hasNext(); running a constructor happens on next(). Everything the diagram calls lazy lives in that gap.
The cache is the loader, not the VM. Two calls to load for the same service build two independent caches, which is why caching a loader VM-wide is a known way to hold the wrong class loader alive.
Lazy is the point: names are cheap, instances are not
A ServiceLoader loads and instantiates providers on demand and keeps what it has built in a cache. iterator() returns an iterator, hasNext() locates the next provider by reading configuration and loading the class, and next() is what constructs the instance. That split is what lets you look at a provider type before paying for it.
Two consequences follow from it. Iterating is never free, because each next() runs a constructor. And because of the cache, a second pass over the same loader hands back the same instances in the order they were first built, rather than fresh ones.
- Caching is per ServiceLoader instance. A new
load(...)call starts with an empty cache, andreload()clears an existing one so the next iteration locates providers from scratch. - A ServiceLoader is not thread-safe. The javadoc says so directly: share one only with external synchronisation, or give each thread its own loader.
- `stream()` (Java 9 and later) exposes `Provider` objects. You can filter on
provider.type()and callget()only on the ones worth constructing. - `findFirst()` is the shortest existence check, and it still instantiates the first provider only.
Iteration is a constructor call per provider. If the loop only needs to know whether any provider exists, filter the Provider stream instead of iterating instances.
Service loading · names first, instances on demand
Code on the class path calls ServiceLoader.load(Codec.class). The caller is in the unnamed module, which needs no uses declaration, and the lookup will start from the calling thread's context class loader once iteration begins.
Names are illustrative; the behaviour is the documented one: providers are located lazily, instantiated by next(), cached per loader instance, and a duplicate name in a configuration file is served once.
What makes a class a provider, and what breaks it
The provider contract is small, and every violation surfaces as the same error type with a different cause.
| Requirement | Class path provider | Module provider |
|---|---|---|
| visibility | a public class, and not an inner class | a public class; its package does not need to be exported |
| creation | a public no-arg constructor | a public no-arg constructor, or a public static provider() method |
| assignability | must implement or extend the service type | provider() may return any subtype, so the class itself need not implement the service |
| automatic modules | not applicable | no provider() method is supported: a provider constructor is required |
- A `provider()` method is a Java 9 addition. It is a public static method named
providerwith no parameters whose return type is assignable to the service, so a provider can hand out an existing singleton or a subclass without being that subclass itself. - Failures are `ServiceConfigurationError`, an Error rather than a checked exception. A provider that will not load, a class that is not a subtype, a missing public constructor, a malformed configuration file: each one surfaces from
hasNext()ornext()while you iterate, and from the lookup methods that trigger loading. - A failure does not reliably stop the walk. The javadoc promises only a best effort to continue with later providers. Treat the error as a deployment bug to fix, not a condition to recover from.
ServiceConfigurationError means the deployment is wrong, not the request. Every cause is a fixable packaging mistake: a name that does not load, a class that is not a provider, or a constructor that is not public.
Where you already meet it
The mechanism is older than modules (Java 6) and older than most of the libraries in a modern build, so it appears in places you would not describe as plugins.
- JDBC: since JDBC 4, driver jars register themselves through
META-INF/services/java.sql.Driver, which is whyClass.forName("org.postgresql.Driver")is a relic. The jdbc-fundamentals lesson covers the driver side in full. - Charsets: a
CharsetProvideron the class path letsCharset.forNamefind an encoding the JDK does not ship with. - Locale data:
LocaleServiceProviderimplementations supply locale-sensitive services such as date formats and calendar systems. - XML: the JAXP factories,
DocumentBuilderFactoryandTransformerFactory, can be selected through the same service-provider mechanism, which is how an XML implementation is swapped without touching code. - Logging: SLF4J 2 discovers its binding through a service provider, which turned a build-time dependency into a deployment choice.
The pattern appears wherever a platform promises one interface and vendors supply implementations. Once you can read a META-INF/services entry, a good share of the ecosystem's wiring stops being mysterious.
Publishing your own SPI: a short playbook
When you own the interface side, the following order keeps callers out of trouble.
- Define the smallest interface providers must implement, in a package you are willing to version, because providers compile against it and it is therefore public API.
- Document the provider contract: public class, public no-arg constructor or a
provider()method, and whether you intend the service to be a factory rather than a direct implementation. - Look providers up with
ServiceLoader.load(YourService.class), and preferfindFirst()or a filteredstream()when one implementation is enough. - Decide and enforce an order in your own code, because the API will not. A first-one-wins rule belongs where the selection happens, visible to the next reader.
- Give
ServiceConfigurationErrora message that names the service and the provider, since the reader's next question is which jar to fix.
ServiceLoader buys you compiled-against interfaces with wiring decided at startup. Publish the interface, document the contract, and let the deployment name the implementation.
The loop that only wanted to know whether a provider exists
A loop like for (Codec codec : ServiceLoader.load(Codec.class)) { found = true; break; } reads as a cheap check and is not one: the enhanced for loop calls next(), and next() constructs the first provider, which may open a socket, load a dictionary or size a buffer pool. findFirst() still instantiates one, because it is defined in terms of iterator. ServiceLoader.load(Codec.class).stream().findAny().isPresent() only locates a provider and reads its type. Loading class names is cheap; building instances is the expensive half, and stream() is the only API that lets you separate the two.
Interview angles
What is an SPI, and how does ServiceLoader implement one?+
An SPI is a published interface plus a documented way for other jars to supply implementations. ServiceLoader is the discovery half: it reads provider names from META-INF/services files or from provides directives in module descriptors, then loads and instantiates the providers as you iterate.
When is a provider instance created?+
On next(), never before. hasNext() locates the next provider (configuration is read and the class is loaded), next() constructs it, and the loader caches the instance so later iterations reuse it. findFirst() instantiates exactly one provider, and stream() instantiates none until you call get().
Common misconception: That iterating a ServiceLoader is the same as listing provider class names. Only stream() gives you the class without the instance.
What must a provider class look like?+
Public and not an inner class, with a public no-arg constructor, and it must implement the service. A module provider may instead declare a public static no-arg provider() method whose return type is assignable to the service, and then the class itself need not implement it.
The constructor or factory method has to be public because the caller is outside the provider's package: the loader is the entity that instantiates it. A provider deployed as an automatic module must use a constructor, since provider() methods are not supported there.
What does the uses directive buy a modular consumer?+
It records that the module consumes the service, and ServiceLoader.load checks it: a caller in a named module that does not declare uses fails with ServiceConfigurationError naming the module, and the launcher uses the same declaration to decide which provider modules to resolve.
module com.acme.app {
requires com.acme.api;
uses com.acme.api.Codec; // without this line load() fails: com.acme.app does not declare uses
}A ServiceConfigurationError says a provider cannot be instantiated. What do you check first?+
The constructor. The message for this case names the class and says there is no public no-arg constructor, which is usually a non-public class, a constructor with parameters, or a provider that only has a provider() method deployed as an automatic module.