ServiceLoader and providers
What you will learn
ServiceLoader connects a service interface to installed implementations without the caller constructing a particular implementation. A service can have zero, one or several providers. Discovery is not a security sandbox: provider code runs with application permissions.
- Separate a service contract from a trusted provider.
- Understand classpath descriptors and named-module service declarations.
- Handle zero providers and inspect a provider before instantiation.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Compile with -proc:none to disable annotation processors. Run only these reviewed examples in a fresh lab-owned directory. Service fixtures create and clean up fixed local registration resources. No external plugins or private access bypass.
Load a fixed trusted provider
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public interface Formatter { String format(String input); } public static class Upper implements Formatter { public Upper() {} public String format(String input) { return input.toUpperCase(Locale.ROOT); } } public interface Missing {} // Only fixed, reviewed class names; no external JARs or user input. static void withProvider(boolean register, java.util.function.Consumer<ClassLoader> action) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-service-"); Path meta = dir.resolve("META-INF"); Path services = meta.resolve("services"); Path descriptor = services.resolve(Formatter.class.getName()); try { Files.createDirectories(services); if (register) Files.writeString(descriptor, Upper.class.getName() + "\n", StandardCharsets.UTF_8); try (URLClassLoader loader = new URLClassLoader(new URL[]{dir.toUri().toURL()}, Main.class.getClassLoader())) { action.accept(loader); } } finally { Files.deleteIfExists(descriptor); Files.deleteIfExists(services); Files.deleteIfExists(meta); Files.delete(dir); } } public static void main(String[] args) throws Throwable { withProvider(true, loader -> { Formatter f = ServiceLoader.load(Formatter.class, loader).findFirst().orElseThrow(); System.out.println(f.format("invoice")); }); }}Expected output:
INVOICEThe caller depends on Formatter, not on Upper construction. The only configured implementation is Upper.
Service contract and registration
Define a small interface (Formatter here), implement it in a public concrete class with a public no-argument constructor for classpath deployment, and register the binary class name in a UTF-8 file named META-INF/services/<service binary name>. Each line names a provider; comments begin with #. For ordinary top-level types the binary name is package-qualified; nested classes use $. A classpath deployment usually packages this descriptor as a resource in a reviewed JAR. The self-contained examples write only that fixed resource to a fresh directory, use a loader whose parent contains the reviewed implementation, and close the loader before cleanup. No class files are written or obtained externally.
Discovery and selection
ServiceLoader.load(service, loader) selects a specific class loader; the shorter overload uses the thread context class loader. Iteration and findFirst lazily instantiate providers; stream exposes Provider descriptors whose type() gives provider type information and get() obtains an instance. Empty discovery is normal; decide whether absence is optional or a startup error. ServiceConfigurationError signals malformed configuration or provider creation problems; it is not simply an empty result. Providers are cached by the loader, and reload clears the cache. Do not rely on arbitrary discovery order for business priority or share a ServiceLoader unsafely between threads.
Named modules and trust
A named consumer module declares uses for its service and requires the API module if separate. The provider module declares provides service with implementation and need not export its implementation package. Named modules can also use a supported public static provider factory; the classpath convention uses the public no-argument constructor. Exports and opens are different from service binding. Module directives are conceptual here; module-path labs come later. Review provider artifacts and their dependencies before deployment; inspecting type() before get() is not a sandbox and discovery itself may load classes. No user-supplied class names, remote URLs, dynamic JAR installs or access bypasses are allowed.
Handle missing service
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public interface Formatter { String format(String input); } public static class Upper implements Formatter { public Upper() {} public String format(String input) { return input.toUpperCase(Locale.ROOT); } } public interface Missing {} // Only fixed, reviewed class names; no external JARs or user input. static void withProvider(boolean register, java.util.function.Consumer<ClassLoader> action) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-service-"); Path meta = dir.resolve("META-INF"); Path services = meta.resolve("services"); Path descriptor = services.resolve(Formatter.class.getName()); try { Files.createDirectories(services); if (register) Files.writeString(descriptor, Upper.class.getName() + "\n", StandardCharsets.UTF_8); try (URLClassLoader loader = new URLClassLoader(new URL[]{dir.toUri().toURL()}, Main.class.getClassLoader())) { action.accept(loader); } } finally { Files.deleteIfExists(descriptor); Files.deleteIfExists(services); Files.deleteIfExists(meta); Files.delete(dir); } } public static void main(String[] args) throws Throwable { withProvider(false, loader -> { Optional<Formatter> f = ServiceLoader.load(Formatter.class, loader).findFirst(); System.out.println(f.map(x -> x.format("invoice")).orElse("no formatter")); }); }}Expected output:
no formatterAn empty loader is handled explicitly; it is not an exception or an implicit default provider.
Inspect a provider descriptor
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public interface Formatter { String format(String input); } public static class Upper implements Formatter { public Upper() {} public String format(String input) { return input.toUpperCase(Locale.ROOT); } } public interface Missing {} // Only fixed, reviewed class names; no external JARs or user input. static void withProvider(boolean register, java.util.function.Consumer<ClassLoader> action) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-service-"); Path meta = dir.resolve("META-INF"); Path services = meta.resolve("services"); Path descriptor = services.resolve(Formatter.class.getName()); try { Files.createDirectories(services); if (register) Files.writeString(descriptor, Upper.class.getName() + "\n", StandardCharsets.UTF_8); try (URLClassLoader loader = new URLClassLoader(new URL[]{dir.toUri().toURL()}, Main.class.getClassLoader())) { action.accept(loader); } } finally { Files.deleteIfExists(descriptor); Files.deleteIfExists(services); Files.deleteIfExists(meta); Files.delete(dir); } } public static void main(String[] args) throws Throwable { withProvider(true, loader -> { ServiceLoader.Provider<Formatter> p = ServiceLoader.load(Formatter.class, loader).stream().findFirst().orElseThrow(); System.out.println(p.type().getSimpleName()); System.out.println(p.get().format("daily")); }); }}Expected output:
UpperDAILYThe stream supplies provider metadata; get obtains the service object. Both operations concern the fixed trusted fixture.
Common mistakes
Do not treat the first discovered provider as a universal priority rule, silently ignore configuration errors, or load a plugin chosen by untrusted input. Never assume a public classpath provider is also automatically accessible in a named module.
Practice
Run discovery twice using separate loaders: one with the registered provider and one without. Print READY when present and MISSING otherwise.
Expected output:
READYMISSINGCompare your answer with the manual practice criteria.
Official reading: ServiceLoader · ServiceLoader.Provider · JLS 7. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ServiceLoader and providers — knowledge check
Original metadata, reflection and service discovery questions. Java 21-compatible scope.
What is the classpath registration location?
What does findFirst return when no provider is found?
What does Provider.get do?
Which directive declares a consumer service in a named module?
Does ServiceLoader sandbox provider code?