Java ServiceLoader: Loading Pluggable Service Implementations
Build pluggable Java applications with java.util.ServiceLoader: define a service interface, write providers, register them in META-INF/services or with provides/uses in module-info, iterate lazily, select providers with stream() and Provider.type(), and use findFirst.
kvi5hnuCode Sprout team member8 min readOn this page
Sometimes you develop an application with a service architecture: the core program defines what a service must do, and separately packaged providers supply implementations. Platforms such as OSGi take this approach to the extreme and are used in IDEs, application servers and other complex software. They go well beyond this course, but the JDK has a simple built-in mechanism for loading services: java.util.ServiceLoader. It's well supported by the Java Platform Module System, too.
When providing a service, a program often wants to give the service designer freedom in how to implement its features. It can also be useful to have multiple implementations to choose from. ServiceLoader makes it easy to load services that conform to a common interface. The JDK itself relies on it for JDBC drivers, java.nio.file file system providers, charset providers, XML parsers and System.LoggerFinder logging backends. Libraries use it the same way; SLF4J 2, for example, finds its logging backend through ServiceLoader.

Step 1: Define the Service Interface
Define an interface (or, if you prefer, a superclass) with the methods each instance of the service should provide. Suppose your service provides encryption:
package com.example.cipher;
public interface Cipher {
byte[] encrypt(byte[] source, byte[] key);
byte[] decrypt(byte[] source, byte[] key);
int strength();
}
Step 2: Write Providers
The service provider supplies one or more classes that implement the service:
package com.example.cipher.impl;
import com.example.cipher.Cipher;
public class CaesarCipher implements Cipher {
public byte[] encrypt(byte[] source, byte[] key) {
var result = new byte[source.length];
for (int i = 0; i < source.length; i++)
result[i] = (byte) (source[i] + key[0]);
return result;
}
public byte[] decrypt(byte[] source, byte[] key) {
return encrypt(source, new byte[] { (byte) -key[0] });
}
public int strength() { return 1; }
}
The implementing classes can be in any package, not necessarily the service interface's package. Each must be public and have a public no-argument constructor, because the loader creates instances reflectively.
Step 3: Register the Providers
On the class path, add the names of the provider classes to a UTF-8 encoded text file in the META-INF/services directory, whose name is the fully qualified interface name. Here, the file META-INF/services/com.example.cipher.Cipher contains
com.example.cipher.impl.CaesarCipher
com.example.cipher.impl.XorCipher
one class per line (# starts a comment). You could provide just one class, or several and pick among them later. The file is packaged in the provider's JAR. With Maven or Gradle, put it under src/main/resources/META-INF/services/.
With modules, you declare providers in module-info.java instead, and the consuming module declares that it uses the service:
module com.example.cipher {
exports com.example.cipher;
uses com.example.cipher.Cipher;
provides com.example.cipher.Cipher
with com.example.cipher.impl.CaesarCipher, com.example.cipher.impl.XorCipher;
}
In a module, a provider may alternatively have a public static method named provider() that returns the instance, which lets it be a singleton or have a non-public constructor. Modules are covered in the last part of this course.
Step 4: Load and Use the Services
With that preparation done, the program initializes a service loader, once:
public static ServiceLoader<Cipher> cipherLoader = ServiceLoader.load(Cipher.class);
The loader's iterator method returns an iterator through all provided implementations (iterators are covered in the collections part). The easiest way is an enhanced for loop. In the loop, pick an appropriate object to carry out the service:
public static Cipher getCipher(int minStrength) {
for (Cipher cipher : cipherLoader) // implicitly calls cipherLoader.iterator()
if (cipher.strength() >= minStrength) return cipher;
return null;
}
The iteration is lazy: provider classes are loaded and instantiated as the iterator advances, and the loader caches the instances it has created.
Selecting a provider without instantiating it
Alternatively, use streams to locate the desired service. The stream method (Java 9) yields a stream of ServiceLoader.Provider descriptors. A provider has two methods: type() returns the provider class, and get() returns an instance. If you select a provider by its type, you call only type, so no service instances are created unnecessarily:
public static Optional<Cipher> getCipher2(String simpleName) {
return cipherLoader.stream()
.filter(descr -> descr.type().getSimpleName().equals(simpleName))
.findFirst()
.map(ServiceLoader.Provider::get);
}
You could also filter by an annotation on the provider class, such as descr.type().isAnnotationPresent(Fast.class).
Finally, if you're willing to take any service instance, simply call findFirst:
Optional<Cipher> cipher = cipherLoader.findFirst();
Optional is a container that may or may not hold a value; it's covered with streams. Its orElseGet method takes a Supplier, the same lazy-default idea you met in the lambdas article.
A complete run
With the interface, two providers and the META-INF/services file above, plus this test class:
package com.example.cipher;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.ServiceLoader;
public class ServiceLoaderTest {
public static final ServiceLoader<Cipher> cipherLoader = ServiceLoader.load(Cipher.class);
public static void main(String[] args) {
for (Cipher c : cipherLoader)
System.out.println("found " + c.getClass().getName() + ", strength " + c.strength());
Cipher cipher = getCipher(2);
String message = "Meet me at the toga party.";
byte[] bytes = cipher.encrypt(message.getBytes(StandardCharsets.UTF_8), new byte[] { 3, 7 });
String decrypted = new String(cipher.decrypt(bytes, new byte[] { 3, 7 }), StandardCharsets.UTF_8);
System.out.println(cipher.getClass().getSimpleName() + ": " + decrypted);
System.out.println(getCipher2("CaesarCipher").map(c -> c.getClass().getSimpleName()).orElse("none"));
System.out.println(cipherLoader.findFirst().isPresent());
}
// getCipher and getCipher2 as shown above
}
compiling and running gives:
$ javac -d classes $(find src -name "*.java")
$ cp -r src/META-INF classes/
$ java -cp classes com.example.cipher.ServiceLoaderTest
found com.example.cipher.impl.CaesarCipher, strength 1
found com.example.cipher.impl.XorCipher, strength 3
XorCipher: Meet me at the toga party.
CaesarCipher
true
Adding a new cipher now means dropping another JAR on the class path. The application code doesn't change at all.
Try it in one file
A single-file program has no META-INF/services entry, so the loader finds no providers. That's a realistic case your code must handle, for example by falling back to a default implementation:
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Solution {
// a service interface; in a real project, providers are listed in META-INF/services
public interface Cipher {
byte[] encrypt(byte[] source, byte[] key);
byte[] decrypt(byte[] source, byte[] key);
int strength();
}
public static class CaesarCipher implements Cipher {
public CaesarCipher() { } // providers need a public no-arg constructor
public byte[] encrypt(byte[] source, byte[] key) {
var result = new byte[source.length];
for (int i = 0; i < source.length; i++) result[i] = (byte) (source[i] + key[0]);
return result;
}
public byte[] decrypt(byte[] source, byte[] key) {
return encrypt(source, new byte[] { (byte) -key[0] });
}
public int strength() { return 1; }
}
public static void main(String[] args) {
ServiceLoader<Cipher> loader = ServiceLoader.load(Cipher.class);
// no META-INF/services/Solution$Cipher file here, so no providers are found
System.out.println("providers found: " + loader.stream().count());
Optional<Cipher> first = loader.findFirst();
System.out.println("findFirst: " + first.isPresent());
// a sensible fallback when nothing is installed
Cipher cipher = first.orElseGet(CaesarCipher::new);
byte[] secret = cipher.encrypt("HAL".getBytes(StandardCharsets.UTF_8), new byte[] { 1 });
System.out.println(new String(secret, StandardCharsets.UTF_8) + " -> "
+ new String(cipher.decrypt(secret, new byte[] { 1 }), StandardCharsets.UTF_8));
// the file name a provider JAR would need
System.out.println("META-INF/services/" + Cipher.class.getName());
}
}
providers found: 0
findFirst: false
IBM -> HAL
META-INF/services/Solution$Cipher
The API
| Method | Since | Purpose |
|---|---|---|
static <S> ServiceLoader<S> load(Class<S> service) | 6 | Creates a loader for implementations of the service, using the thread's context class loader |
static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader) | 6 | Uses a specific class loader, e.g. for plugins loaded from a directory |
Iterator<S> iterator() | 6 | Lazily loads and instantiates providers as it advances |
Stream<ServiceLoader.Provider<S>> stream() | 9 | Provider descriptors, so a provider can be chosen before instantiation |
Optional<S> findFirst() | 9 | The first available provider, if any |
void reload() | 6 | Clears the cache, so newly installed providers are found |
Provider.type(), Provider.get() | 9 | The provider class, and an instance of it |
Common questions
Why does ServiceLoader find no providers?
The most common causes are: the META-INF/services file is missing from the JAR or has the wrong name (it must be the fully qualified interface name), the provider JAR isn't on the class path, a fat JAR overwrote the file instead of merging it, or, with modules, the consumer lacks uses or the provider lacks provides ... with.
Is ServiceLoader the same as dependency injection?
No. ServiceLoader only discovers implementations and creates them with a no-argument constructor or a provider() method. Dependency-injection frameworks such as Spring or CDI also wire dependencies, manage lifecycles and scopes, and configure objects. ServiceLoader is ideal for simple plugin points, especially in libraries that shouldn't depend on a framework.
Does ServiceLoader create a new object every time I iterate?
A single ServiceLoader instance caches the providers it has already instantiated, so iterating again returns the same objects. Calling reload(), or creating a new loader with ServiceLoader.load, discovers and instantiates them again.
How do I pick one provider out of several?
Use loader.stream(), filter on Provider.type() (for example by class name or annotation) and call get() only on the one you choose. Alternatively, give the service interface a method such as name() or priority() and pick after instantiating.
Can a provider be a singleton?
In a named module, yes. Declare a public static method named provider() that returns the instance, and ServiceLoader calls it instead of a constructor. On the class path, a provider must have a public no-argument constructor, but that object can delegate to a shared instance.
Summary
- A service is an interface (or abstract class). Providers are public classes implementing it, with public no-arg constructors (or a static
provider()method in modules). - Register providers on the class path in
META-INF/services/<fully.qualified.InterfaceName>, or withprovides ... with ...inmodule-info.java. Consumers in modules declareuses. ServiceLoader.load(Service.class)creates the loader once. Iterate it to instantiate providers lazily, usestream()withProvider.type()to choose without instantiating, orfindFirst()to take any.- Always handle the case that no provider is installed.
Practice Questions
Your service interface is org.acme.spi.Storage and the provider is org.acme.s3.S3Storage. What file must the provider JAR contain, and with what content?
META-INF/services/org.acme.spi.Storage, containing the line org.acme.s3.S3Storage.
Why does stream() with Provider.type() avoid work compared to iterating the loader?
Iterating instantiates every provider it passes. Provider.type() only loads the class, so you can inspect it, for example its name or annotations, and call get() only on the provider you choose.
What requirements must a provider class meet on the class path?
It must be public, implement or extend the service type, and have a public no-argument constructor.
What's the module-system equivalent of META-INF/services, for both the provider and the consumer?
The provider module declares provides Service with Impl; and the consumer module declares uses Service; in their module-info.java files.
Why is ServiceLoader a good fit for JDBC drivers?
Applications code against java.sql interfaces, and each database vendor ships a JAR that registers its java.sql.Driver implementation. DriverManager uses ServiceLoader to find drivers, so adding a driver JAR is enough; no Class.forName("...Driver") call is needed anymore.
Previous: Java Local, Anonymous and Static Nested Classes
Next: Java Dynamic Proxies: Implementing Interfaces at Runtime
Related reading
- Java Reflection: Invoking Methods and Writing Generic Array Code
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources
- Processing Java Annotations at Runtime with Reflection
- Java Local, Anonymous and Static Nested Classes

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.