Java Modules (JPMS): Build and Run ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-28

Java Services: provides, uses and ServiceLoader

A service in modular Java is an interface (or abstract class) that can have any number of implementations in different modules. A consumer module declares uses and gets the implementations through java.util.ServiceLoader without knowing about them in advance. A provider module declares provides ... with and does not export its implementation. This is how plugins, drivers and swappable implementations are built without hard dependencies.

module com.shop.card {
    requires com.shop.payment;
    provides com.shop.payment.PaymentMethod with com.shop.card.CardPayment;
}

module com.shop.app {
    requires com.shop.payment;
    uses com.shop.payment.PaymentMethod;   // com.shop.card is not mentioned
}

This lesson continues Java Modules: module-info, requires, exports and opens. Below: the roles of the modules, the rules for provides and uses, how the JVM finds providers, which methods ServiceLoader has, and what happens without modules, through META-INF/services. All examples were checked on JDK 25.

1. Why services exist

A plain requires ties modules tightly: if com.shop.app requires com.shop.card, the program does not start without that module, and adding a new payment method means changing and recompiling com.shop.app. Services turn the dependency around:

  • the consumer depends only on the interface, not on implementations;
  • implementations are plugged in just by putting their modules on the module path;
  • implementation classes stay in non-exported packages and cannot be called directly.

The JDK itself works this way. The java.sql module declares uses java.sql.Driver, and every JDBC driver registers its implementation as a provider. That is why you have not needed Class.forName("com.mysql.cj.jdbc.Driver") since Java 6; see JDBC drivers.

2. Three roles: API, provider and consumer

Module Contains Writes in module-info.java
API (com.shop.payment) The service interface exports the package with the interface
Provider (com.shop.card) An implementation of the interface requires the API module and provides Interface with Implementation;
Consumer (com.shop.app) Code with ServiceLoader.load() requires the API module and uses Interface;

Note what is missing: the consumer does not require the provider, and the provider neither exports nor opens the implementation package. The API and the provider can be one module, but then the application depends on the module with the implementation, and the decoupling is lost.

3. Example: the shop's payment methods

The API module with the service interface:

// src/com.shop.payment/module-info.java
module com.shop.payment {
    exports com.shop.payment;
}

// src/com.shop.payment/com/shop/payment/PaymentMethod.java
package com.shop.payment;

public interface PaymentMethod {
    String name();
    String pay(int amount);
}

The provider module for card payments:

// src/com.shop.card/module-info.java
module com.shop.card {
    requires com.shop.payment;
    provides com.shop.payment.PaymentMethod with com.shop.card.CardPayment;
}

// src/com.shop.card/com/shop/card/CardPayment.java
package com.shop.card;

import com.shop.payment.PaymentMethod;

public class CardPayment implements PaymentMethod {
    public String name() { return "card"; }
    public String pay(int amount) { return "paid " + amount + " by card"; }
}

The consumer module iterates over all implementations it finds:

// src/com.shop.app/module-info.java
module com.shop.app {
    requires com.shop.payment;
    uses com.shop.payment.PaymentMethod;
}

// src/com.shop.app/com/shop/app/Checkout.java
package com.shop.app;

import com.shop.payment.PaymentMethod;
import java.util.ServiceLoader;

public class Checkout {
    public static void main(String[] args) {
        ServiceLoader<PaymentMethod> loader = ServiceLoader.load(PaymentMethod.class);
        for (PaymentMethod m : loader) {
            System.out.println(m.name() + ": " + m.pay(100));
        }
    }
}
javac -d out --module-source-path src -m com.shop.app,com.shop.payment,com.shop.card
java -p out -m com.shop.app/com.shop.app.Checkout
card: paid 100 by card

Now add a second provider module, com.shop.wallet, with two implementations. The code of com.shop.app does not change and is not recompiled: it is enough to put the new module into out:

module com.shop.wallet {
    requires com.shop.payment;
    provides com.shop.payment.PaymentMethod
        with com.shop.wallet.WalletPayment, com.shop.wallet.CryptoPayment;
}
java -p out -m com.shop.app/com.shop.app.Checkout
wallet: paid 100 from wallet
crypto (bitcoin): paid 100 in bitcoin
card: paid 100 by card

Implementations of one module come in the order listed after with. The order between different modules is not guaranteed: you cannot rely on wallet coming before card.

4. provides ... with: requirements for an implementation

The compiler checks every implementation in provides. A class qualifies if one of two conditions holds:

  1. Through a constructor: a public non-abstract top-level class, or a static nested class, that implements the service interface and has a public no-argument constructor.
  2. Through a provider() method: a class with a public static no-argument method named provider that returns the service type or a subtype. In this case the class itself does not have to implement the interface, and its constructor may be private.

If a class has both, provider() wins. That is how CryptoPayment from the example works: the no-argument constructor would pick the default network, but ServiceLoader called provider(), hence crypto (bitcoin) in the output:

public class CryptoPayment implements PaymentMethod {
    private final String network;

    public CryptoPayment() { this("default"); }
    private CryptoPayment(String network) { this.network = network; }

    public static CryptoPayment provider() { return new CryptoPayment("bitcoin"); }

    public String name() { return "crypto (" + network + ")"; }
    public String pay(int amount) { return "paid " + amount + " in " + network; }
}

A provider() method is handy when the implementation is a singleton, is built by a factory, or is even an anonymous class:

public class PaymentFactory {          // does not implement PaymentMethod itself
    public static PaymentMethod provider() {
        return new PaymentMethod() {
            public String name() { return "factory"; }
            public String pay(int amount) { return "paid " + amount + " via factory"; }
        };
    }
}
// provides com.shop.payment.PaymentMethod with com.shop.card.PaymentFactory;  compiles

Three more rules for provides:

  • All implementations of one service go into one directive, separated by commas. Two provides directives for the same interface are the error multiple 'provides' for service PaymentMethod.
  • One service per directive. provides A, B with Impl; does not compile; another service needs its own provides.
  • The implementation package does not need to be exported. ServiceLoader creates the object even though the package is closed. Exporting is allowed, but it opens the implementation for direct use.

5. uses: declaring a consumer

The uses directive allows a module to look up implementations of a service through ServiceLoader. Without it the code compiles but fails when load() is called:

Exception in thread "main" java.util.ServiceConfigurationError: com.shop.payment.PaymentMethod: module com.shop.app does not declare `uses`

This is one of the most common traps: the error is invisible at build time. The rules for uses:

  • uses does not replace requires. The service type must be accessible: without requires com.shop.payment neither the import nor the uses line compiles: package com.shop.payment is not visible.
  • A service can be an interface, an abstract class or a regular class, including a final one. An enum cannot: uses java.time.DayOfWeek; gives the service definition is an enum.
  • You cannot repeat uses for the same type: duplicate uses.
  • One module can both use and provide the same service: uses X; next to provides X with Y; compiles.

6. How the JVM finds providers: service binding

At startup the JVM builds the module graph from the main module along the requires directives. Then it performs service binding: for every uses it adds to the graph all modules on the module path that declare provides for that service. The --show-module-resolution option makes this visible:

java -p out --show-module-resolution -m com.shop.app/com.shop.app.Checkout
root com.shop.app file:///.../out/com.shop.app/
com.shop.app requires com.shop.payment file:///.../out/com.shop.payment/
com.shop.app binds com.shop.wallet file:///.../out/com.shop.wallet/
com.shop.app binds com.shop.card file:///.../out/com.shop.card/
...

The binds lines are providers that entered the graph without any requires and without --add-modules. Three consequences follow:

  • Remove a provider module from the module path, and the program still starts; it just finds fewer implementations.
  • No providers at all is not an error: the for loop runs zero times, and findFirst() returns an empty Optional.
  • If a provider itself requires a module that is missing, the JVM does not start and reports FindException: a bound module is checked as strictly as a regular dependency.

7. ServiceLoader methods: iterator, findFirst, stream, reload

ServiceLoader<S> implements Iterable<S>, so you can walk it with a for loop. The main methods:

Method Returns Creates objects
ServiceLoader.load(S.class) A loader for service S No, the lookup is lazy
iterator(), for loop Provider instances Yes, while iterating; caches them
findFirst() Optional<S> with the first provider Yes, from the same cache
stream() Stream<ServiceLoader.Provider<S>> No, until get() is called
Provider.type() The provider class No
Provider.get() A provider instance Yes, a new one each time
reload() — Clears the cache; the next iteration creates new objects

stream() lets you pick an implementation by class without creating extra objects. To see when objects are created, add System.out.println("CardPayment created"); to the CardPayment constructor:

ServiceLoader<PaymentMethod> loader = ServiceLoader.load(PaymentMethod.class);

List<String> types = loader.stream()
        .map(p -> p.type().getSimpleName())
        .toList();
System.out.println("types: " + types);       // types: [CardPayment], no object created yet

PaymentMethod a = loader.findFirst().get();  // CardPayment created
PaymentMethod b = loader.findFirst().get();  // nothing: taken from the cache
System.out.println("same: " + (a == b));     // same: true

loader.reload();
PaymentMethod c = loader.findFirst().get();  // CardPayment created
System.out.println("after reload: " + (a == c));   // after reload: false

iterator() and findFirst() share the cache, while stream() does not use it: loader.stream().findFirst().get().get() creates a new object every time and is not the same instance as the one from iterator().

If there are no providers, findFirst() returns an empty Optional, stream().count() returns 0, and calling loader.iterator().next() directly throws NoSuchElementException. A ServiceLoader instance is not thread-safe: in multithreaded code either create one per thread or collect the providers into an immutable list right away (thread safety is covered in the Threads module).

8. Services in --describe-module output

The java --describe-module command shows services as separate lines:

java -p out -d com.shop.wallet
com.shop.wallet file:///.../out/com.shop.wallet/
requires com.shop.payment
requires java.base mandated
provides com.shop.payment.PaymentMethod with com.shop.wallet.WalletPayment com.shop.wallet.CryptoPayment
contains com.shop.wallet

java -p out -d com.shop.app
com.shop.app file:///.../out/com.shop.app/
requires java.base mandated
requires com.shop.payment
uses com.shop.payment.PaymentMethod
contains com.shop.app

The implementations in the provides line are separated by spaces, not commas. The line contains com.shop.wallet confirms that the implementation package is not exported. JDK modules show their services the same way, for example uses java.sql.Driver in java.sql.

9. Services without module-info: META-INF/services

ServiceLoader appeared in Java 6, long before modules. On the class path a provider is registered with a file in the JAR: the path META-INF/services/ plus the fully qualified interface name, containing the fully qualified implementation names, one per line:

# file META-INF/services/com.shop.payment.PaymentMethod
com.shop.card.CardPayment
java -cp "api;card;app" com.shop.app.Checkout
card: paid 100 by card

Without that file the same run prints nothing: the CardPayment class is on the class path, but ServiceLoader does not know about it. On the class path uses is not needed, because the code is in the unnamed module. How the registration methods work together:

Where the provider is How it is registered Does ServiceLoader find it
A named module on the module path provides ... with Yes
A named module with only a META-INF/services file The file is ignored No, even with --add-modules
A plain JAR on the module path (automatic module) META-INF/services becomes provides Yes
A plain JAR on the class path META-INF/services Yes, for a modular consumer too

For an automatic module this is visible in its description: jar --describe-module --file card-legacy.jar prints the line provides com.shop.payment.PaymentMethod with com.shop.card.CardPayment, taken from the file. Automatic modules and migration are covered in a separate lesson of this module. Creating JAR files is covered in How to Create and Use JAR Files in Java.

10. Does it compile? Typical errors

The module com.shop.card requires com.shop.payment. Each row is a directive added to its module-info.java. Results were obtained on JDK 25:

Directive or implementation class Result
with CardPayment: public, implements the interface, public constructor Compiles
with Outer.Nested: a public static nested class Compiles
with PaymentFactory: only public static PaymentMethod provider() Compiles
with PrivateCtor: a private constructor, but a provider() method Compiles
with AbstractPayment: an abstract class Error: the service implementation is an abstract class
with HiddenPayment: a package-private constructor Error: the no arguments constructor of the service implementation is not public
with Outer.Inner: an inner (non-static) class Error: the service implementation is an inner class
with Receipt: does not implement the interface, no provider() Error: must be a subtype of the service interface type, or have a public static no-args method named "provider"
with WrongFactory: provider() returns String Error: the "provider" method return type must be a subtype of the service interface type
Two provides directives for PaymentMethod Error: multiple 'provides' for service
with CardPayment, CardPayment Error: duplicate provides
provides PaymentMethod, Runnable with CardPayment Error: 'with' expected
provides ... with CardPayment; + uses PaymentMethod; Compiles

Frequently asked questions

Why does ServiceLoader find nothing?

Check three things. The provider module is on the module path and declares provides Interface with Implementation for exactly the interface you load. If the code runs from the class path, the provider's JAR contains a META-INF/services/ file named after the fully qualified interface. And a META-INF/services file does not help a named module: it needs provides.

What does the error "does not declare `uses`" mean?

The module called ServiceLoader.load() for a service without declaring uses in module-info.java. The code still compiles; the ServiceConfigurationError appears only at run time. Add uses with the fully qualified name of the service interface.

Does the consumer need requires for the provider module?

No, and that is the whole point of services. The JVM itself adds to the graph all modules that declare provides for a used service (the binds lines in --show-module-resolution output). The consumer needs only requires for the module with the interface, plus uses.

Why use a provider() method instead of a constructor?

It lets you return a pre-built object (a singleton), an object with parameters or an implementation from a factory, while keeping the class constructor private. If a class has both a public static provider() method and a public no-argument constructor, ServiceLoader calls provider().

In what order does ServiceLoader return implementations?

Implementations of one module come in the order listed after with. The order between different modules is not defined and may depend on the environment. If order matters, add a priority method to the service interface and sort the providers yourself.

Comments

Please log in or register to have a possibility to add comment.