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.Driverjava.util.ServiceLoader
Providers are registered in one of two ways:
- On the class path, a JAR contains a file
listing implementation class names, one per line, withMETA-INF/services/<fully qualified service name> for comments. Each class needs a public no-argument constructor.# - In a module (Java 9),
declaresmodule-info.java , and the module that looks the service up declaresprovides Service with Impl; . A provider class may then offer auses Service; method instead of a constructor.public static provider()
ServiceLoader.load(Service.class, loader)ServiceLoader
| Feature | Since | Best for |
|---|---|---|
META-INF/services | Java 1.3 (JAR specification); public API in Java 6 | Libraries on the class path |
ServiceLoader.loadreload() | Java 6 | Finding and using all providers |
providesusesmodule-infoprovider() | Java 9 | Modular applications |
stream()Provider.type()get()findFirst() | Java 9 | Choosing a provider before instantiating it |
ServiceLoader.load(ModuleLayer, Class) | Java 9 | Plugins 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
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:
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
over the plugin directory, both greeters were found and called, in the order of the services file.URLClassLoader - The services file is named after the binary name of the service,
for a nested interface, and lists implementation class names.PluginDiscovery$Greeter withstream() reported the classes without creating them, and the last lookup picked the French provider by a property. Selecting by type before callingProvider::type avoids constructing providers you will not use.get()- The one-argument
uses the thread's context class loader, which is why frameworks set it before loading plugins.ServiceLoader.load(Service.class)
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.
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:
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 9) exposes command-line tools such asjava.util.spi.ToolProvider ,javac ,jar andjlink as services that run inside the current JVM, without starting a process. The programs on this page use it to compile their plugins.jpackage- File systems are providers too. Besides the default
scheme, the JDK installsfile (the zip file system in modulejar ) andjdk.zipfs , which reads the classes of the running JDK.jrt - Other JDK services include JDBC drivers (
, found byjava.sql.Driver since JDBC 4.0, which is whyDriverManager for drivers is no longer needed), charset providers andClass.forName .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.
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:
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
; theload() constructor ran only when the iterator reached it.Gzip - Each broken entry threw
fromServiceConfigurationError orhasNext() , 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.next() - The second iteration printed no constructor line: the same
returned its cached instance. AfterServiceLoader the cache was cleared and the provider was constructed again. A newreload() object also starts with an empty cache.ServiceLoader - A
is not thread-safe. Load providers once at start-up and share the resulting list, rather than sharing the loader.ServiceLoader
Providers in modules: provides, uses and provider()
In the module system, registration moves from text files into module-info.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:
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
was requested, yetshapes.app resolved all three modules. Binding followsresolveAndBind clauses to modules thatuses the service, so a provider module does not need to be required by anyone.provide has no public constructor; the module system called itsCircles method instead, which can return a cached instance or an anonymous class. For such providers,public static provider() reports the method's return type, hereProvider.type() , not the declaring class.shapes.api.Shape- The provider's package is not exported, so no other module can use the
class directly; onlyCircles can reach it. That strong encapsulation is the main advantage of module-based registration. A modular JAR may still contain aServiceLoader file for use on the class path.META-INF/services - The program calls
andname() 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.area()
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.
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:
(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
first and calledProvider.type() 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 sameget() .ServiceLoader - For cheap selection by metadata, an annotation on the provider class works well: read it from
without instantiating anything, as described on theProvider.type()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
above, so the application can choose among several providers without instantiating heavy ones.language() - 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
to choose between competing implementations.findFirst() - 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
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.META-INF/services
Choosing a discovery mechanism
| Situation | Use |
|---|---|
| Library extension points on the class path | META-INF/servicesServiceLoader |
| Modular application | providesusesprovider() |
| Plugins loaded and unloaded at run time | A URLClassLoaderServiceLoader |
| Choose a provider without creating all of them | stream()Provider.type()get() |
| Tolerate broken providers | Iterate with an explicit iterator and catch ServiceConfigurationError |
| Dependency injection with configuration | A DI framework such as Spring, which has its own discovery |
See module-info