Quiz: Java Services: provides, uses and ServiceLoader
Study the lesson first: Java Services: provides, uses and ServiceLoader
Total: 6 questions
1. What is a service in modular Java, and what three roles do modules play?
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:
requiresthe API module andprovides Interface with Implementation;. It neither exports nor opens the implementation package. - The consumer module calls
ServiceLoader.load():requiresthe API module anduses 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?
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
staticnested class, that implements the service interface and has apublicno-argument constructor. Otherwise you getthe service implementation is an abstract class,... is an inner classorthe no arguments constructor of the service implementation is not public. - Through a
provider()method: apublic staticno-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 beprivate. Ifprovider()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?
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.
usesdoes not replacerequires: withoutrequiresfor the API module neither theimportnor theusesline compiles (package ... is not visible).- A service can be an interface, an abstract class or a regular class, including a
finalone. An enum cannot:uses java.time.DayOfWeek;givesthe service definition is an enum. - You cannot repeat
usesfor the same type:duplicate uses. - One module can both use and provide the same service:
uses X;next toprovides 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)?
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
forloop runs zero times, andfindFirst()returns an emptyOptional. - 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?
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 theforloop create provider instances while iterating and cache them; a second traversal returns the same objects.findFirst()returns anOptional<S>with the first provider, taken from the same cache.stream()returns aStream<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?
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; aMETA-INF/servicesfile in it is ignored, even with--add-modules. - A plain JAR on the module path (an automatic module): the file becomes
provides, asjar --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.