Java Module Services: Service Provider Interface, ServiceLoader, uses and provides (OCP 21)
Module services for the OCP 21 exam: the service provider interface, service locator, consumer and service provider, the uses and provides directives, ServiceLoader load, findFirst and stream with Provider, the rules for provider classes, and which directives each part needs.
kvi5hnuCode Sprout team member9 min readOn this page
Say a café app wants to show a drinks menu, and different suppliers will add drinks over time. If the menu code names each drink class, every new supplier means changing and recompiling the menu. Services remove that dependency. The app defines what a drink is, and implementations are discovered at run time, from whatever modules happen to be on the module path. Code that depends only on an interface and finds its implementations at run time is called loosely coupled.
The four parts
The exam describes a service setup with four kinds of modules. They can be combined in fewer modules, but the questions usually keep each part separate:
| Part | What it is | Example | Part of the service? |
|---|---|---|---|
| Service provider interface | The interface (or abstract class) that defines the service, plus any types it uses | cafe.api with interface Drink | Yes |
| Service locator | Code that finds implementations using ServiceLoader | cafe.finder with class Menu | Yes |
| Consumer (client) | Code that gets implementations from the locator and uses them | cafe.guest with class Order | No |
| Service provider | An implementation of the interface | cafe.tea with class Chai | No |
The service is the interface plus the lookup code. Implementations aren't part of it, and that's the point: they can be added, removed or replaced without touching the service.

1. The service provider interface
package cafe.api;
public interface Drink {
String name();
int price();
}
module cafe.api {
exports cafe.api;
}
The only directive needed is exports, so that the other modules can see Drink. If the interface mentioned other types, such as a Receipt record, those would belong here too and also be exported. The service type can also be an abstract class, though exam questions use interfaces.
2. The service locator
package cafe.finder;
import cafe.api.Drink;
import java.util.*;
public class Menu {
public static Optional<Drink> first() {
return ServiceLoader.load(Drink.class).findFirst();
}
public static List<Drink> all() {
List<Drink> list = new ArrayList<>();
for (Drink d : ServiceLoader.load(Drink.class))
list.add(d);
return list;
}
}
module cafe.finder {
exports cafe.finder;
requires cafe.api;
uses cafe.api.Drink;
}
The locator needs three directives:
exports cafe.finder;so that consumers can callMenu.requires cafe.api;so that it can compile againstDrink.uses cafe.api.Drink;to declare that this module looks up implementations ofDrink.usestakes a type name, not a package or module name.
The ServiceLoader API
ServiceLoader<S> is a final class in java.util that implements Iterable<S>. For the exam, know these members:
| Member | What it does |
|---|---|
static <S> ServiceLoader<S> load(Class<S> service) | Creates a loader for the service type. Nothing is instantiated yet. |
iterating with for / iterator() | Creates each provider object when it's reached, and caches it for the next iteration of the same loader |
Optional<S> findFirst() | The first available provider, or an empty Optional |
Stream<ServiceLoader.Provider<S>> stream() | A stream of Provider handles. Nothing is created until you call get(). |
Provider.get() | Creates (or returns) the provider object |
Provider.type() | The provider's class, available without creating an object |
reload() | Clears the cache so that providers are found again |
The type of stream() is the classic trap. It isn't a Stream<Drink>, so a get() step is needed:
OptionalInt cheapest = ServiceLoader.load(Drink.class)
.stream() // Stream<ServiceLoader.Provider<Drink>>
.map(ServiceLoader.Provider::get) // Stream<Drink>
.mapToInt(Drink::price)
.min();
Writing .stream().mapToInt(Drink::price) without get doesn't compile. The stream holds providers, not drinks.
When no implementation is found, nothing fails: the loop runs zero times, findFirst() is empty and the stream is empty. Don't rely on the order of providers that come from different modules. Within one provides directive, they appear in the order listed. Calling load scans the module graph, so real applications usually keep the result instead of calling load repeatedly.
3. The consumer
package cafe.guest;
import cafe.finder.Menu;
public class Order {
public static void main(String[] args) {
System.out.println(Menu.first().map(d -> d.name()).orElse("(none)"));
System.out.println(Menu.all().size() + " drinks");
}
}
module cafe.guest {
requires cafe.finder;
requires cafe.api; // or: cafe.finder says 'requires transitive cafe.api;'
}
The consumer only needs requires. It calls the locator and works with Drink objects, so it must read both modules. The second requires can be dropped if the locator declares requires transitive cafe.api;. The consumer needs no uses, because it isn't the code calling ServiceLoader.
With only these three modules on the module path, the program runs fine and prints (none) and 0 drinks.
4. A service provider
package cafe.tea.impl;
public class Chai implements cafe.api.Drink {
public String name() { return "chai"; }
public int price() { return 3; }
}
module cafe.tea {
requires cafe.api;
provides cafe.api.Drink with cafe.tea.impl.Chai;
}
requires cafe.api;becauseChaiimplementsDrink.provides <service type> with <implementation class>;registers the implementation. Both names are fully qualified types.- No
exports. The packagecafe.tea.implstays hidden. Nobody ever writesnew Chai(), becauseServiceLoadercreates it.
Put cafe.tea on the module path and run again, without recompiling anything else. Now the output is chai and 1 drinks. The java launcher includes every module on the module path that provides a service some resolved module uses. This is called service binding.
Rules for the implementation class
javac checks the provides directive strictly. Every rule below was verified against javac 21 and 25:
| Rule | Error if broken |
|---|---|
The class must be public and not abstract | Chai is not public in cafe.tea.impl / the service implementation is an abstract class |
It needs a public no-argument constructor... | the service implementation does not have a default constructor / ...constructor of the service implementation is not public |
...or a public static no-argument method named provider() that returns the service type | (with neither: must be a subtype of the service interface type, or have a public static no-args method named "provider") |
It must be in the same module as the provides directive | service implementation must be defined in the same module as the provides directive |
Each service may appear in only one provides per module | multiple 'provides' for service Drink |
To supply several implementations, list them in one directive, separated by commas:
provides cafe.api.Drink with cafe.tea.impl.Chai, cafe.tea.impl.Mint;
The provider() method lets a class keep its constructor private or return a shared instance:
public class Espresso implements cafe.api.Drink {
private Espresso() { }
public static cafe.api.Drink provider() { return new Espresso(); }
...
}
When a provider() method exists, ServiceLoader calls it instead of a constructor.
Which directives does each part need?
| Part | exports | requires | uses | provides |
|---|---|---|---|---|
| Service provider interface | ✓ | |||
| Service locator | ✓ | ✓ | ✓ | |
| Consumer | ✓ | |||
| Service provider | ✓ | ✓ |
This completes the directive list from articles 73 and 74:
| Directive | Description |
|---|---|
exports p; / exports p to m; | Makes package p available to other modules |
requires m; / requires transitive m; | Declares a dependency on module m |
opens p; / opens p to m; | Allows reflection on package p |
provides S with C; | Supplies implementation C of service type S |
uses S; | Declares that this module looks up implementations of S |
What's current
ServiceLoaderhas existed since Java 6. Before modules, providers were registered with a text fileMETA-INF/services/<service type name>listing implementation class names. That mechanism still works for JARs on the class path. Inside a named module,providesreplaces it.findFirst(),stream(),ServiceLoader.Providerand theprovider()method convention were added in Java 9 together with modules, and are unchanged in Java 21 and 25.- Many JDK features are services. For example,
java.sql.Driverimplementations and theToolProviderused by the example program are both looked up throughServiceLoader.
Exam traps from this article
A complete example
This program writes five café modules to a temporary folder: the interface, the locator, the consumer and two providers. One provider supplies two drinks, and the other uses a provider() factory method. It compiles them all and runs the consumer twice, without and then with the provider modules, the way java -p ... -m cafe.guest/cafe.guest.Order binds services. Then it shows the run-time error when the locator lacks uses, and the compile error for a provider without a no-arg constructor.
import java.io.*;
import java.lang.module.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
public class Solution {
static Path root;
static void write(String file, String code) throws IOException {
Path p = root.resolve("src").resolve(file);
Files.createDirectories(p.getParent());
Files.writeString(p, code);
}
static void compileAll(String label) throws IOException {
List<String> args = new ArrayList<>(List.of(
"-d", root.resolve("out").toString(),
"--module-source-path", root.resolve("src").toString()));
try (var files = Files.walk(root.resolve("src"))) {
files.filter(f -> f.toString().endsWith(".java")).sorted()
.forEach(f -> args.add(f.toString()));
}
var err = new StringWriter();
int code = ToolProvider.findFirst("javac").orElseThrow()
.run(new PrintWriter(Writer.nullWriter()), new PrintWriter(err), args.toArray(String[]::new));
System.out.println(label + " -> " + (code == 0 ? "compiles" : "FAILS"));
err.toString().lines().filter(l -> l.contains("error:"))
.forEach(l -> System.out.println(" " + l.substring(l.indexOf("error:"))));
}
// Like: java -p <modules> -m cafe.guest/cafe.guest.Order
static void runGuest(String... modules) throws Exception {
Path[] dirs = Arrays.stream(modules).map(m -> root.resolve("out").resolve(m)).toArray(Path[]::new);
ModuleLayer boot = ModuleLayer.boot();
// resolveAndBind also pulls in modules that 'provide' a service someone 'uses',
// which is what the java launcher does.
Configuration cf = boot.configuration()
.resolveAndBind(ModuleFinder.of(dirs), ModuleFinder.of(), Set.of("cafe.guest"));
ModuleLayer.Controller ctl = ModuleLayer.defineModulesWithOneLoader(
cf, List.of(boot), ClassLoader.getSystemClassLoader());
ModuleLayer layer = ctl.layer();
ctl.addExports(layer.findModule("cafe.guest").orElseThrow(), "cafe.guest", Solution.class.getModule());
ClassLoader loader = layer.findLoader("cafe.guest");
Thread.currentThread().setContextClassLoader(loader); // the launcher does this too
try {
loader.loadClass("cafe.guest.Order").getMethod("main", String[].class)
.invoke(null, (Object) new String[0]);
} catch (java.lang.reflect.InvocationTargetException e) {
Throwable c = e.getCause();
System.out.println(" " + c.getClass().getSimpleName() + ": " + c.getMessage());
} finally {
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
}
}
static void deleteTree(Path dir) throws IOException {
try (var paths = Files.walk(dir)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
}
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("cafe");
try {
// 1. Service provider interface
write("cafe.api/cafe/api/Drink.java", """
package cafe.api;
public interface Drink {
String name();
int price();
}
""");
write("cafe.api/module-info.java", "module cafe.api { exports cafe.api; }\n");
// 2. Service locator
write("cafe.finder/cafe/finder/Menu.java", """
package cafe.finder;
import cafe.api.Drink;
import java.util.*;
public class Menu {
private Menu() { }
public static Optional<Drink> first() {
return ServiceLoader.load(Drink.class).findFirst();
}
public static List<Drink> all() {
List<Drink> list = new ArrayList<>();
for (Drink d : ServiceLoader.load(Drink.class)) list.add(d);
return list;
}
public static List<String> typesOnly() {
return ServiceLoader.load(Drink.class).stream()
.map(p -> p.type().getSimpleName())
.sorted().toList();
}
public static OptionalInt cheapest() {
return ServiceLoader.load(Drink.class).stream()
.map(ServiceLoader.Provider::get)
.mapToInt(Drink::price)
.min();
}
}
""");
write("cafe.finder/module-info.java", """
module cafe.finder {
exports cafe.finder;
requires transitive cafe.api;
uses cafe.api.Drink;
}
""");
// 3. Consumer
write("cafe.guest/cafe/guest/Order.java", """
package cafe.guest;
import cafe.finder.Menu;
public class Order {
public static void main(String[] args) {
System.out.println(" first: " + Menu.first().map(d -> d.name()).orElse("(none)"));
System.out.println(" types: " + Menu.typesOnly());
var names = Menu.all().stream().map(d -> d.name() + " $" + d.price()).sorted().toList();
System.out.println(" all: " + names);
System.out.println(" cheapest: " + Menu.cheapest());
}
}
""");
write("cafe.guest/module-info.java", """
module cafe.guest {
requires cafe.finder;
}
""");
// 4. Two independent service providers
write("cafe.tea/cafe/tea/impl/Chai.java", """
package cafe.tea.impl;
public class Chai implements cafe.api.Drink {
public String name() { return "chai"; }
public int price() { return 3; }
}
""");
write("cafe.tea/cafe/tea/impl/Mint.java", """
package cafe.tea.impl;
public class Mint implements cafe.api.Drink {
public String name() { return "mint tea"; }
public int price() { return 2; }
}
""");
write("cafe.tea/module-info.java", """
module cafe.tea {
requires cafe.api;
provides cafe.api.Drink with cafe.tea.impl.Chai, cafe.tea.impl.Mint;
}
""");
write("cafe.coffee/cafe/coffee/Espresso.java", """
package cafe.coffee;
public class Espresso implements cafe.api.Drink {
private Espresso() { } // not usable by ServiceLoader...
public static cafe.api.Drink provider() { // ...so it supplies a factory
return new Espresso();
}
public String name() { return "espresso"; }
public int price() { return 4; }
}
""");
write("cafe.coffee/module-info.java", """
module cafe.coffee {
requires cafe.api;
provides cafe.api.Drink with cafe.coffee.Espresso;
}
""");
compileAll("== Build all five modules");
System.out.println("\n== Run with only api, finder and guest on the module path");
runGuest("cafe.api", "cafe.finder", "cafe.guest");
System.out.println("\n== Same compiled code, now with cafe.tea and cafe.coffee added");
runGuest("cafe.api", "cafe.finder", "cafe.guest", "cafe.tea", "cafe.coffee");
System.out.println("\n== Locator without 'uses cafe.api.Drink;'");
Path finderInfo = root.resolve("src/cafe.finder/module-info.java");
String finder = Files.readString(finderInfo);
Files.writeString(finderInfo, finder.replace(" uses cafe.api.Drink;\n", ""));
compileAll(" build");
runGuest("cafe.api", "cafe.finder", "cafe.guest", "cafe.tea");
Files.writeString(finderInfo, finder);
System.out.println("\n== Provider whose constructor takes an argument");
Path chai = root.resolve("src/cafe.tea/cafe/tea/impl/Chai.java");
Files.writeString(chai, Files.readString(chai).replace(
"public class Chai implements cafe.api.Drink {",
"public class Chai implements cafe.api.Drink {\n public Chai(int size) { }"));
compileAll(" build");
} finally {
deleteTree(root);
}
}
}
Output:
== Build all five modules -> compiles
== Run with only api, finder and guest on the module path
first: (none)
types: []
all: []
cheapest: OptionalInt.empty
== Same compiled code, now with cafe.tea and cafe.coffee added
first: chai
types: [Chai, Drink, Mint]
all: [chai $3, espresso $4, mint tea $2]
cheapest: OptionalInt[2]
== Locator without 'uses cafe.api.Drink;'
build -> compiles
ServiceConfigurationError: cafe.api.Drink: module cafe.finder does not declare `uses`
== Provider whose constructor takes an argument
build -> FAILS
error: the service implementation does not have a default constructor: Chai
Points to notice:
- The first run found nothing, and it didn't fail. With the two provider modules added to the module path, the same compiled locator and consumer found three drinks.
typescame fromProvider.type()without creating any objects. ForEspresso, which uses aprovider()method,type()reports the method's declared return type,Drink, notEspresso.cheapestusedstream().map(ServiceLoader.Provider::get).mapToInt(...).- Removing
usesstill compiled, but the firstServiceLoader.loadcall threwServiceConfigurationError. - A
Chai(int size)constructor without a no-arg alternative is rejected at compile time by theprovidescheck. - The example uses
Configuration.resolveAndBind. Plainresolvedoesn't pull in provider modules that nobody requires, while thejavalauncher always binds.
Common questions
Can the interface and the locator be in the same module?
Yes. Then that module has exports, uses and possibly requires, all in one declaration. A module can even both provide and use the same service.
Does the consumer need uses if it calls ServiceLoader itself?
Yes. Whichever module calls ServiceLoader.load needs uses. In the four-module setup, that's the locator.
Can two different modules provide the same service?
Yes. That's the normal case, and ServiceLoader returns all of them. Only within one module may the service appear in a single provides directive.
Is the service provider interface required to be an interface? No. An abstract class works too, as long as the providers extend it.
Summary
- A service consists of a service provider interface and a service locator. Providers and consumers are separate.
- Service provider interface:
exports. Locator:exports,requires,uses. Consumer:requires. Provider:requires,provides ... with .... ServiceLoader.load(Type.class)is iterable and hasfindFirst().stream()yieldsProviderobjects that needget().- Provider classes need a public no-arg constructor or a public static
provider()method, and must live in the providing module. - New providers are picked up at run time without recompiling the service or its consumers.
Practice quiz
Test yourself with the module services quiz: 10 exam-style questions with explanations.
Previous: Java Module Declarations: requires, requires transitive, exports and opens (OCP 21)
Next: Java Module Commands: describe-module, jdeps, jmod and jlink (OCP 21)
Related reading
- Java Module Declarations: requires, requires transitive, exports and opens (OCP 21)
- Java Modules: Benefits, module-info.java, Compiling, Running and Packaging (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- OCP Java 21 Exam Guide (1Z0-830): Format, Objectives, Strategy and Study Plan

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.