ServiceLoader and service providers

ServiceLoader finds implementations of an interface that the application did not know about when it was compiled. It is how JDBC finds database drivers, how the JDK finds its tools and file systems, and how many libraries support plugins. This page explains the mechanism and its two registration styles, loads providers compiled at run time, lists the JDK's own services, shows lazy instantiation, caching and broken providers, and wires a provider through module declarations.

Contents

How ServiceLoader finds providers

A service is an interface or abstract class that an application defines, such as java.sql.Driver. A provider is a class, usually in another JAR, that implements it. java.util.ServiceLoader (Java 6; the mechanism existed inside the JDK since 1.3) connects the two at run time, so the application never names the implementation class in its code. Dropping a JAR onto the class path is enough to add a provider.

Providers are registered in one of two ways:

  • On the class path, a JAR contains a file META-INF/services/<fully qualified service name> listing implementation class names, one per line, with # for comments. Each class needs a public no-argument constructor.
  • In a module (Java 9), module-info.java declares provides Service with Impl;, and the module that looks the service up declares uses Service;. A provider class may then offer a public static provider() method instead of a constructor.

ServiceLoader.load(Service.class, loader) reads every matching registration visible through the class loader, but creates nothing yet. Providers are found and instantiated lazily as you iterate, and each instance is cached in that ServiceLoader object.

ServiceLoader features
FeatureSinceBest for
META-INF/services registrationJava 1.3 (JAR specification); public API in Java 6Libraries on the class path
ServiceLoader.load, iteration, reload()Java 6Finding and using all providers
provides and uses in module-info, provider() factory methodsJava 9Modular applications
stream() with Provider.type() and get(), findFirst()Java 9Choosing a provider before instantiating it
ServiceLoader.load(ModuleLayer, Class)Java 9Plugins loaded into their own module layer

The programs below ran on JDK 21.

A plugin found through META-INF/services

The application owns a Greeter interface. Two providers are compiled at run time into a separate directory, as if they shipped in their own JAR, and registered with a services file. Loading first through the application's own class path shows what happens when the plugin directory is not visible.

Java
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ServiceLoader;
import java.util.spi.ToolProvider;

public class PluginDiscovery {

    // The service: an interface the application owns
    public interface Greeter {
        String language();

        String greet(String name);
    }

    // Two providers, written and compiled separately, as if shipped in their own jars
    static final String ENGLISH = """
            public class EnglishGreeter implements PluginDiscovery.Greeter {
                public String language() { return "en"; }
                public String greet(String name) { return "Hello, " + name; }
            }
            """;
    static final String FRENCH = """
            public class FrenchGreeter implements PluginDiscovery.Greeter {
                public String language() { return "fr"; }
                public String greet(String name) { return "Bonjour, " + name; }
            }
            """;

    public static void main(String[] args) throws Exception {
        Path plugins = Files.createTempDirectory("plugins");
        compile(plugins, "EnglishGreeter", ENGLISH);
        compile(plugins, "FrenchGreeter", FRENCH);

        // Registration: one file named after the service, listing implementation classes
        Path services = plugins.resolve("META-INF/services");
        Files.createDirectories(services);
        Files.writeString(services.resolve("PluginDiscovery$Greeter"),
                "EnglishGreeter\nFrenchGreeter\n");

        long before = ServiceLoader.load(Greeter.class).stream().count();
        System.out.println("providers on the plain classpath: " + before);

        URL[] path = {plugins.toUri().toURL()};
        ClassLoader parent = PluginDiscovery.class.getClassLoader();
        try (URLClassLoader loader = new URLClassLoader(path, parent)) {
            ServiceLoader<Greeter> found = ServiceLoader.load(Greeter.class, loader);
            for (Greeter g : found) {                               // instantiates each provider
                System.out.println(g.language() + ": " + g.greet("Ada"));
            }
            // Java 9: inspect provider types without instantiating them
            found.stream()
                    .map(ServiceLoader.Provider::type)
                    .forEach(t -> System.out.println("provider class: " + t.getSimpleName()));
            Greeter french = found.stream().map(ServiceLoader.Provider::get)
                    .filter(g -> g.language().equals("fr")).findFirst().orElseThrow();
            System.out.println("chosen by language: " + french.greet("Linus"));
        }
    }

    static void compile(Path dir, String name, String source) throws IOException {
        Path file = dir.resolve(name + ".java");
        Files.writeString(file, source);
        String classPath = System.getProperty("java.class.path");
        int rc = ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err,
                "-cp", classPath, "-d", dir.toString(), file.toString());
        if (rc != 0) {
            throw new IllegalStateException("compile failed for " + name);
        }
    }
}

Output:

Output
providers on the plain classpath: 0
en: Hello, Ada
fr: Bonjour, Ada
provider class: EnglishGreeter
provider class: FrenchGreeter
chosen by language: Bonjour, Linus
  • Through the application class loader, 0 providers were found: discovery only sees what the given class loader can see. With a URLClassLoader over the plugin directory, both greeters were found and called, in the order of the services file.
  • The services file is named after the binary name of the service, PluginDiscovery$Greeter for a nested interface, and lists implementation class names.
  • stream() with Provider::type reported the classes without creating them, and the last lookup picked the French provider by a property. Selecting by type before calling get() avoids constructing providers you will not use.
  • The one-argument ServiceLoader.load(Service.class) uses the thread's context class loader, which is why frameworks set it before loading plugins.

Services inside the JDK

The JDK uses the same mechanism for its own extension points. The program lists two of them and runs a compiler found as a service.

Java
import java.nio.charset.Charset;
import java.nio.file.spi.FileSystemProvider;
import java.util.ServiceLoader;
import java.util.TreeSet;
import java.util.spi.ToolProvider;

public class JdkServices {

    public static void main(String[] args) {
        // java.util.spi.ToolProvider (Java 9): the JDK's command-line tools as services
        TreeSet<String> tools = new TreeSet<>();
        ServiceLoader.load(ToolProvider.class).forEach(t -> tools.add(t.name()));
        System.out.println("ToolProvider services: " + tools);

        // File system providers: "file" is built in, "jar" (zipfs) is found as a service
        TreeSet<String> schemes = new TreeSet<>();
        for (FileSystemProvider p : FileSystemProvider.installedProviders()) {
            schemes.add(p.getScheme());
        }
        System.out.println("file system schemes:   " + schemes);

        // Running a tool found through the service: javac's version
        ToolProvider javac = ToolProvider.findFirst("javac").orElseThrow();
        System.out.print("javac --version via ToolProvider: ");
        javac.run(System.out, System.err, "--version");
        System.out.println("default charset: " + Charset.defaultCharset());
    }
}

Output:

Output
ToolProvider services: [jar, javac, javadoc, javap, jdeps, jlink, jmod, jpackage]
file system schemes:   [file, jar, jrt]
javac --version via ToolProvider: javac 21.0.12.1
default charset: UTF-8
  • java.util.spi.ToolProvider (Java 9) exposes command-line tools such as javac, jar, jlink and jpackage as services that run inside the current JVM, without starting a process. The programs on this page use it to compile their plugins.
  • File systems are providers too. Besides the default file scheme, the JDK installs jar (the zip file system in module jdk.zipfs) and jrt, which reads the classes of the running JDK.
  • Other JDK services include JDBC drivers (java.sql.Driver, found by DriverManager since JDBC 4.0, which is why Class.forName for drivers is no longer needed), charset providers and System.LoggerFinder.

Lazy loading, caching and broken providers

A services file lists four codecs: one good provider and three broken ones, with no usable constructor, of the wrong type, and missing altogether. The good provider prints when it is constructed, so the output shows when instantiation happens.

Java
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.spi.ToolProvider;

public class LazyAndErrors {

    public interface Codec {
        String name();
    }

    static final String GOOD = """
            public class Gzip implements LazyAndErrors.Codec {
                public Gzip() { System.out.println("    (Gzip constructed)"); }
                public String name() { return "gzip"; }
            }
            """;
    static final String NO_DEFAULT_CTOR = """
            public class Zstd implements LazyAndErrors.Codec {
                public Zstd(int level) { }
                public String name() { return "zstd"; }
            }
            """;
    static final String WRONG_TYPE = """
            public class Brotli {
                public Brotli() { }
            }
            """;

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("codecs");
        compile(dir, "Gzip", GOOD);
        compile(dir, "Zstd", NO_DEFAULT_CTOR);
        compile(dir, "Brotli", WRONG_TYPE);
        Path services = Files.createDirectories(dir.resolve("META-INF/services"));
        Files.writeString(services.resolve("LazyAndErrors$Codec"),
                "# one provider per line, comments allowed\nGzip\nZstd\nBrotli\nMissing\n");

        try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                LazyAndErrors.class.getClassLoader())) {
            ServiceLoader<Codec> codecs = ServiceLoader.load(Codec.class, loader);
            System.out.println("load() returned; nothing constructed yet");

            // Iterate defensively: each bad entry throws ServiceConfigurationError on its own
            Iterator<Codec> it = codecs.iterator();
            while (true) {
                try {
                    if (!it.hasNext()) {
                        break;
                    }
                    System.out.println("  provider: " + it.next().name());
                } catch (ServiceConfigurationError e) {
                    System.out.println("  skipped: " + e.getMessage());
                }
            }

            // A second pass reuses the cached instance: no new constructor call
            System.out.println("second iteration:");
            for (Codec c : codecs) {
                System.out.println("  provider: " + c.name());
                break;
            }
            codecs.reload();                      // clears the cache
            System.out.println("after reload():");
            for (Codec c : codecs) {
                System.out.println("  provider: " + c.name());
                break;
            }
        }
    }

    static void compile(Path dir, String name, String source) throws IOException {
        Path file = dir.resolve(name + ".java");
        Files.writeString(file, source);
        int rc = ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err,
                "-cp", System.getProperty("java.class.path"), "-d", dir.toString(),
                file.toString());
        if (rc != 0) {
            throw new IllegalStateException("compile failed for " + name);
        }
    }
}

Output:

Output
load() returned; nothing constructed yet
    (Gzip constructed)
  provider: gzip
  skipped: LazyAndErrors$Codec: Zstd Unable to get public no-arg constructor
  skipped: LazyAndErrors$Codec: Brotli not a subtype
  skipped: LazyAndErrors$Codec: Provider Missing not found
second iteration:
  provider: gzip
after reload():
    (Gzip constructed)
  provider: gzip
  • Nothing was constructed by load(); the Gzip constructor ran only when the iterator reached it.
  • Each broken entry threw ServiceConfigurationError from hasNext() or next(), with a message naming the provider and the problem. The iterator can continue past the error, so catching it per entry lets one bad JAR on the class path disable only itself, not the whole feature. A plain for-each loop would have stopped at the first error.
  • The second iteration printed no constructor line: the same ServiceLoader returned its cached instance. After reload() the cache was cleared and the provider was constructed again. A new ServiceLoader object also starts with an empty cache.
  • A ServiceLoader is not thread-safe. Load providers once at start-up and share the resulting list, rather than sharing the loader.

Providers in modules: provides, uses and provider()

In the module system, registration moves from text files into module-info.java. The program compiles three modules at run time, an API, a provider and an application that uses the service, and loads them into a new module layer, the same way plugin hosts load modular plugins.

Java
import java.io.IOException;
import java.lang.module.Configuration;
import java.lang.module.ModuleFinder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.spi.ToolProvider;

public class ModuleProviders {

    // Three tiny modules: an API, a provider, and the module that uses the service
    static final Map<String, String> SOURCES = Map.of(
            "shapes.api/module-info.java", "module shapes.api { exports shapes.api; }",
            "shapes.api/shapes/api/Shape.java", """
                    package shapes.api;
                    public interface Shape { String name(); double area(); }
                    """,
            "shapes.circle/module-info.java", """
                    module shapes.circle {
                        requires shapes.api;
                        provides shapes.api.Shape with shapes.circle.Circles;
                    }
                    """,
            "shapes.circle/shapes/circle/Circles.java", """
                    package shapes.circle;
                    import shapes.api.Shape;
                    public class Circles {
                        // A static provider() method: the provider needs no public constructor
                        public static Shape provider() {
                            System.out.println("    provider() called");
                            return new Shape() {
                                public String name() { return "unit circle"; }
                                public double area() { return Math.PI; }
                            };
                        }
                    }
                    """,
            "shapes.app/module-info.java", """
                    module shapes.app { requires shapes.api; uses shapes.api.Shape; }
                    """);

    public static void main(String[] args) throws Exception {
        Path src = Files.createTempDirectory("src");
        Path out = Files.createTempDirectory("mods");
        for (var e : SOURCES.entrySet()) {
            Path file = src.resolve(e.getKey());
            Files.createDirectories(file.getParent());
            Files.writeString(file, e.getValue());
        }
        compile(src, out);

        // Build a module layer from the compiled modules, binding services while resolving
        ModuleFinder finder = ModuleFinder.of(out);
        Configuration cf = ModuleLayer.boot().configuration()
                .resolveAndBind(finder, ModuleFinder.of(), Set.of("shapes.app"));
        System.out.println("resolveAndBind pulled in: " + cf.modules().stream()
                .map(m -> m.name()).sorted().toList());
        ModuleLayer layer = ModuleLayer.boot().defineModulesWithOneLoader(cf,
                ClassLoader.getSystemClassLoader());

        Class<?> shape = layer.findLoader("shapes.api").loadClass("shapes.api.Shape");
        ServiceLoader<?> loader = ServiceLoader.load(layer, shape);
        loader.stream().forEach(p -> System.out.println("provider type: " + p.type().getName()
                + " in module " + p.type().getModule().getName()));
        for (Object s : loader) {
            Object name = shape.getMethod("name").invoke(s);
            Object area = shape.getMethod("area").invoke(s);
            System.out.printf("%s has area %.4f%n", name, (double) area);
        }
    }

    static void compile(Path src, Path out) throws IOException {
        int rc = ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err,
                "-d", out.toString(), "--module-source-path", src.toString(),
                "-m", "shapes.api,shapes.circle,shapes.app");
        if (rc != 0) {
            throw new IOException("javac failed");
        }
    }
}

Output:

Output
resolveAndBind pulled in: [shapes.api, shapes.app, shapes.circle]
provider type: shapes.api.Shape in module shapes.api
    provider() called
unit circle has area 3.1416
  • Only shapes.app was requested, yet resolveAndBind resolved all three modules. Binding follows uses clauses to modules that provide the service, so a provider module does not need to be required by anyone.
  • Circles has no public constructor; the module system called its public static provider() method instead, which can return a cached instance or an anonymous class. For such providers, Provider.type() reports the method's return type, here shapes.api.Shape, not the declaring class.
  • The provider's package is not exported, so no other module can use the Circles class directly; only ServiceLoader can reach it. That strong encapsulation is the main advantage of module-based registration. A modular JAR may still contain a META-INF/services file for use on the class path.
  • The program calls name() and area() by reflection only because the API module lives in the new layer, invisible to the program's own code at compile time. A real host would put the API in its own layer.

Choosing among several providers

When more than one provider is installed, the service itself should help the host decide. Here a cache service has three providers with a priority and an availability check; the preferred one, Redis, has the highest priority but its server is down in this run.

Java
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.ServiceLoader;

public class ChoosingProvider {

    // A service with methods that describe the provider, so the host can choose
    public interface Cache {
        int priority();                 // higher wins

        boolean available();            // e.g. "is the Redis server reachable?"

        String name();
    }

    public static class MemoryCache implements Cache {
        public int priority() { return 1; }
        public boolean available() { return true; }
        public String name() { return "in-memory"; }
    }

    public static class RedisCache implements Cache {
        public RedisCache() {
            System.out.println("    (RedisCache constructed: opening connections...)");
        }
        public int priority() { return 10; }
        public boolean available() { return false; }    // server down in this run
        public String name() { return "redis"; }
    }

    public static class DiskCache implements Cache {
        public int priority() { return 5; }
        public boolean available() { return true; }
        public String name() { return "disk"; }
    }

    public static void main(String[] args) throws Exception {
        // Register the three providers in a services file in a separate directory
        Path dir = Files.createTempDirectory("svc");
        Path file = Files.createDirectories(dir.resolve("META-INF/services"))
                .resolve("ChoosingProvider$Cache");
        Files.writeString(file, "ChoosingProvider$MemoryCache\nChoosingProvider$RedisCache\n"
                + "ChoosingProvider$DiskCache\n");

        try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                ChoosingProvider.class.getClassLoader())) {
            ServiceLoader<Cache> caches = ServiceLoader.load(Cache.class, loader);

            Cache best = caches.stream()
                    .map(ServiceLoader.Provider::get)
                    .filter(Cache::available)
                    .max(Comparator.comparingInt(Cache::priority))
                    .orElseThrow();
            System.out.println("chosen: " + best.name() + " (priority " + best.priority() + ")");

            // Filtering on the type first avoids constructing providers you do not want
            System.out.println("only types, then one get():");
            Cache disk = caches.stream()
                    .filter(p -> p.type().getSimpleName().startsWith("Disk"))
                    .map(ServiceLoader.Provider::get)
                    .findFirst()
                    .orElseThrow();
            System.out.println("chosen by type: " + disk.name());
        }
    }
}

Output:

Output
(RedisCache constructed: opening connections...)
chosen: disk (priority 5)
only types, then one get():
chosen by type: disk
  • The host constructed every provider, filtered out the unavailable Redis cache and picked the highest remaining priority: disk, priority 5, ahead of in-memory with 1. Priority plus an availability check is a common way to pick one implementation out of several.
  • Constructing a provider just to ask its priority can be expensive, as the "opening connections" line shows. The second lookup filtered on Provider.type() first and called get() only for the chosen class, so no constructor ran for the others. It also reused the cached disk instance from the first lookup, since both used the same ServiceLoader.
  • For cheap selection by metadata, an annotation on the provider class works well: read it from Provider.type() without instantiating anything, as described on the annotations page.

Design tips and traps

  • Keep the service interface in a small API artifact that both the application and the providers depend on, and load providers with a class loader whose parent can see that API. Otherwise the provider's interface and the application's interface are different classes, and casts fail as shown on the class loading page.
  • Give the service a method that describes the provider, like language() above, so the application can choose among several providers without instantiating heavy ones.
  • Providers are found in class path order. When two JARs provide the same service, which one comes first depends on the order of the class path, so never rely on findFirst() to choose between competing implementations.
  • A provider class must be public with a public no-argument constructor on the class path. A missing constructor fails only at run time, with ServiceConfigurationError.
  • Shading or merging JARs into one "fat JAR" can overwrite one META-INF/services file with another of the same name. Build plugins such as the Maven Shade plugin's services transformer merge them; without that, providers disappear silently.

Choosing a discovery mechanism

Ways to find implementations at run time
SituationUse
Library extension points on the class pathMETA-INF/services and ServiceLoader
Modular applicationprovides and uses, optionally with provider() methods
Plugins loaded and unloaded at run timeA URLClassLoader or module layer per plugin, plus ServiceLoader
Choose a provider without creating all of themstream(), filter on Provider.type(), then get()
Tolerate broken providersIterate with an explicit iterator and catch ServiceConfigurationError per entry
Dependency injection with configurationA DI framework such as Spring, which has its own discovery

See class loading for loaders and isolation, modules for module-info, and JDBC basics for the best-known service in the JDK.