Quiz: Java Services: provides, uses and ServiceLoader

Total: 6 questions

1. 

What is a service in modular Java, and what three roles do modules play?

A service is an interface (or abstract class) that can have any number of implementations in different modules. A consumer gets the implementations through java.util.ServiceLoader without knowing about them in advance. This is how plugins, drivers and swappable implementations are built without hard dependencies.

  • The API module contains the service interface and exports its package (exports).
  • The provider module contains an implementation: requires the API module and provides Interface with Implementation;. It neither exports nor opens the implementation package.
  • The consumer module calls ServiceLoader.load(): requires the API module and uses Interface;. It does not require the provider.

A plain requires ties modules tightly: the program does not start without the required module, and a new implementation means recompiling the consumer. With services a new implementation is plugged in just by putting its module on the module path. The JDK works the same way: java.sql declares uses java.sql.Driver, which is why Class.forName() for a JDBC driver has not been needed since Java 6. 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.

2. 

What are the requirements for an implementation in a provides ... with directive?

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

  • 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. Otherwise you get the service implementation is an abstract class, ... is an inner class or the no arguments constructor of the service implementation is not public.
  • Through a provider() method: a public static no-argument method that returns the service type or a subtype. The class itself then does not have to implement the interface, and its constructor may be private. If provider() returns another type: the "provider" method return type must be a subtype of the service interface type.

If a class has both a public no-argument constructor and provider(), ServiceLoader calls provider(). The method is handy for a singleton, an object with parameters or a factory.

All implementations of one service go into one directive, separated by commas; a second directive for the same interface is multiple 'provides' for service, a repeated class is duplicate provides. One directive covers one service: provides A, B with Impl; does not compile. The implementation package does not need to be exported: ServiceLoader creates the object even from a closed package.

3. 

Why is the uses directive needed, and what happens if you forget it?

uses Interface; allows a module to look up implementations of a service through ServiceLoader. Without it the code compiles but fails when load() is called: java.util.ServiceConfigurationError: ...: module ... does not declare `uses`. The error is invisible at build time, which makes it a common trap.

  • uses does not replace requires: without requires for the API module neither the import nor the uses line compiles (package ... 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.

On the class path uses is not needed, because the code is in the unnamed module.

4. 

How does the JVM find provider modules if the consumer does not require them (service binding)?

At startup the JVM builds the module graph from the main module along the requires directives, and then 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 shows such modules as binds lines, for example com.shop.app binds com.shop.card: they entered the graph without requires and without --add-modules.

  • 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 missing module, the JVM does not start and reports FindException: a bound module is checked as strictly as a regular dependency.

Order: implementations of one module come in the order listed after with; the order between modules is not guaranteed. If order matters, add a priority method to the interface and sort the providers yourself.

5. 

How do the ServiceLoader methods iterator(), findFirst(), stream() and reload() differ?

ServiceLoader.load(S.class) returns a loader and creates nothing: the lookup is lazy. ServiceLoader<S> implements Iterable<S>, so you can walk it with a for loop.

  • iterator() and the for loop create provider instances while iterating and cache them; a second traversal returns the same objects.
  • findFirst() returns an Optional<S> with the first provider, taken from the same cache.
  • stream() returns a Stream<ServiceLoader.Provider<S>> and does not use the cache. Provider.type() gives the provider class without creating an object, which is how you pick an implementation by class. Provider.get() creates a new object each time.
  • reload() clears the cache: the next traversal creates new objects.

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

6. 

How do you register a provider without module-info through META-INF/services, and how do services appear in --describe-module output?

ServiceLoader appeared in Java 6, 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. Without that file the implementation class is on the class path, but ServiceLoader does not know about it.

  • A named module on the module path registers a provider only with provides ... with; a META-INF/services file in it is ignored, even with --add-modules.
  • A plain JAR on the module path (an automatic module): the file becomes provides, as jar --describe-module --file ... shows.
  • A plain JAR on the class path: a modular consumer finds the provider from the file too.

java --describe-module (-d) shows services as separate lines: uses com.shop.payment.PaymentMethod for the consumer and provides com.shop.payment.PaymentMethod with com.shop.wallet.WalletPayment com.shop.wallet.CryptoPayment for the provider, with implementations separated by spaces, not commas. A contains line with the implementation package confirms that it is not exported.

Page 1 of 1