Skip to content
Tutorials Center
My learning

Topics

Lesson 157 of 201 ยท JVM and Advanced Topics

ServiceLoader and the Service Provider Pattern

Learn how Java's ServiceLoader finds plugins at run time, how to register providers with META-INF/services, lazy streams, error handling and design tips.

How does JDBC find the right database driver when you only wrote a URL? How does java.util.logging or an image reader pick up an add-on format? How do JDK tools like javac and jar appear in one list? They all use the same small mechanism: the Service Provider Interface (SPI) pattern and its helper class, java.util.ServiceLoader.

The idea is to separate three roles. A service is an interface (or abstract class) that defines a capability. A provider is a class that implements it, possibly written by someone else, shipped in another JAR. A consumer asks for "all implementations of this service on my path" without ever naming them. Add a JAR and the consumer discovers new behavior; remove it and the behavior disappears. No if statement and no hard-coded class names are needed.

The Modules lesson showed provides and uses in module-info.java. This lesson focuses on the classic class path way of registering providers, which is still what most libraries, frameworks and plain JARs use, and on the behavior of ServiceLoader itself.

The three pieces

Every SPI setup has the same three parts:

  1. The service interface, for example interface Exporter { String format(); void export(Report r); }. It lives in a library or API module that both sides can see.
  2. One or more providers, ordinary classes with a public no-argument constructor that implement the interface.
  3. A registration that tells the loader which classes are providers. On the class path, that is a text file named after the fully qualified interface inside META-INF/services/ in the provider's JAR:
TEXT
META-INF/services/com.example.report.Exporter

with one provider class name per line (fully qualified, # starts a comment):

TEXT
# PDF exporter shipped in pdf-exporter.jar
com.example.pdf.PdfExporter
com.example.pdf.PdfAExporter

The consumer then writes:

Java
ServiceLoader<Exporter> loader = ServiceLoader.load(Exporter.class);
for (Exporter exporter : loader) {
    System.out.println("available format: " + exporter.format());
}

ServiceLoader.load(Class) uses the thread's context class loader, searches every META-INF/services/<interface name> file visible to it (one per JAR, possibly many), and instantiates the listed classes lazily, one at a time as you iterate. load(Class, ClassLoader) lets you choose the loader instead, which is how application servers give each plugin its own world.

A real plugin system in one program

Our runner cannot put several JARs on a class path, but we can build the same structure at run time: compile two plugin classes into a temporary folder, write the registration file by hand, and give ServiceLoader a class loader that sees that folder. The service interface is a real one from the JDK, java.util.spi.ToolProvider, which the javac, jar and javadoc tools implement:

Java Discovering plugins through META-INF/services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at what happened:

  • The consumer code (ServiceLoader.load(ToolProvider.class, loader)) contains no plugin class names at all.
  • The two plugin classes were found only because of the registration file. Delete the two lines and they vanish.
  • The same loader also found the JDK's own tool providers (javac, jar, jdeps...) because the class loader's parent supplies them from the java.base and tool modules. A ServiceLoader merges all registrations visible to its class loader and its parents.
  • stream() gave Provider objects. p.type() returns the implementation class without instantiating it, and p.get() creates the instance. That is useful for filtering on a class (or an annotation on it) before paying for construction.
  • Iteration order follows the order in which the registration files are found (class path order) and, within a file, line order. Do not rely on it for priority; sort explicitly if order matters.

Notice also that the provider classes have no dependency on the consumer, and the consumer never imports them. That is the whole point.

How the loader works

Four facts help you design around it:

  • Lazy and cached. Providers are located and instantiated on first iteration, then cached in the ServiceLoader object. Iterating again returns the same instances. reload() clears the cache so new providers are found.
  • Not thread-safe. A single ServiceLoader instance must not be shared between threads without synchronization. Create one per use, or load all providers once into an immutable list.
  • Class loader matters. If the interface and the plugins are loaded by different loaders (common in servers and test harnesses), ServiceLoader.load(X.class) with the wrong context loader finds nothing. When "my provider is not found" happens, check the class loader first.
  • Provider construction. On the class path the provider class must be public, be a subtype of the service, and have a public no-argument constructor. In a named module you can also write a public static provider() factory method, and the provides clause names the class that has it.

Helper methods keep common cases short: loader.findFirst() returns an Optional with the first provider, and ServiceLoader.load(...).stream() gives you the lazy Provider stream. For "one implementation, with a default" use findFirst().orElseGet(DefaultImpl::new).

When things go wrong

A broken registration does not fail at startup. It fails when you iterate, with a ServiceConfigurationError (an Error, not an Exception). A missing class, a class that does not implement the interface, a constructor that throws, or a malformed line all produce it. Providers listed before the broken line were already delivered, which is why you should catch the error around the whole loop and decide whether to continue:

Java ServiceConfigurationError and reload()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first provider worked, and the error happened as the iterator reached the bad line. The second registration shows that the "not a subtype" check, too, is done only when the class is reached. Both failures name the interface and the offending entry, so the message is usually enough to find the typo. Note how reload() made the loader re-read the registration files; without it the earlier results would have been reused.

For a robust application, wrap discovery like this:

Java
List<Exporter> exporters = new ArrayList<>();
Iterator<Exporter> it = ServiceLoader.load(Exporter.class).iterator();
while (true) {
    try {
        if (!it.hasNext()) {
            break;
        }
        exporters.add(it.next());
    } catch (ServiceConfigurationError e) {
        log.warn("Skipping broken plugin: {}", e.getMessage());   // keep the good ones
    }
}

Design tips

  • Keep the service interface small and stable. It is a public contract between independent teams; changing it breaks every plugin.
  • Make providers cheap to create. The constructor runs during discovery. Do heavy initialization lazily, on first use, or add an init(Config) method to the interface.
  • Return or sort by priority. If several providers might apply (such as two exporters for the same format), give the interface a priority() or supports(Object) method and choose in the consumer.
  • Do not catch Exception only. Remember that failures are ServiceConfigurationErrors.
  • Generate registration files instead of writing them by hand. The @AutoService annotation (Google's auto-service library) and similar annotation processors produce META-INF/services files at compile time, avoiding typos.
  • Prefer it to reflection and Class.forName. Class.forName("com.acme.X") needs the name in code or config and breaks without a recovery path; SPI gives you a list, and the type system checks the interface.

Where it is used

You have already met several examples. JDBC drivers register through META-INF/services/java.sql.Driver, so DriverManager finds them without Class.forName (see JDBC Introduction). SLF4J 2 and Jakarta APIs discover their implementations the same way. The JDK uses it for charset providers, file system providers, java.net.spi name services, and the ToolProvider you just used. The pattern also works well for your own applications: export formats, importers, validators, payment gateways and theme packs are all natural "services".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does a class-path provider JAR register its implementation of com.example.Exporter?

    ServiceLoader reads files named after the fully qualified service interface inside META-INF/services; each non-comment line names a provider class.
  2. 2. What does ServiceLoader.stream() let you do that the plain iterator does not?

    Provider.type() returns the implementation class without creating an instance, so you can filter first and call get() only for the providers you need.
  3. 3. A registration file lists a class that does not exist. When is the problem reported?

    Providers are located lazily. Errors surface during iteration, and providers listed earlier were already returned.
  4. 4. You add a new plugin JAR while the application runs and it is not discovered by an existing ServiceLoader instance. What should you call?

    ServiceLoader caches providers. reload() clears the cache so the next iteration searches again (the class loader must also be able to see the new JAR).
  5. 5. Which requirement applies to a provider class registered on the class path?

    The loader instantiates providers reflectively, so they must be public subtypes of the service and have a public zero-argument constructor.

Summary

  • The service provider pattern splits an API (service interface), implementations (providers) and users (consumers), and ServiceLoader connects them at run time.
  • On the class path, list providers in META-INF/services/<fully qualified interface name>; in modules use provides ... with and uses.
  • Loading is lazy and cached; use stream() and Provider.type() to inspect before instantiating, findFirst() for a default, and reload() to rescan.
  • Providers need a public no-argument constructor (or a provider() method in a module); keep construction cheap.
  • Broken registrations throw ServiceConfigurationError during iteration, so catch it around the loop.
  • Check the class loader first when providers are not found, and do not share one ServiceLoader between threads.

Next: Object-Oriented Design Principles (SOLID), where interfaces and loose coupling, the ideas behind SPI, become design rules.