concept ServiceLoader in category java

appears as: ServiceLoader, ServiceLoader, The ServiceLoader
The Java Module System

This is an excerpt from Manning's book The Java Module System.

In contrast to the unnamed module, all other modules are said to be named. Services provided in META-INF/services are made available to the ServiceLoader. See chapter 10 for an introduction to services and particularly section 10.2.6 for their interaction with the unnamed module.

At run time, the depending module can use the ServiceLoader class to get all provided implementations of a service by calling ServiceLoader.load(${service}.class). The module system then returns a Provider<${service}> for each provider any module in the module graph declares. Figure 10.3 illustrates implementing a Provider.

Figure 10.3 At the center of using services is a specific type, here called Service. The class Provider implements it, and the module containing it declares that with a provides — with directive. Modules consuming services need to declare that with a uses directive. At run time, they can then use the ServiceLoader to get instances of all providers for a given service.

c10_03.png

Despite the fact that the ServiceLoader has been around since Java 6, it hasn’t seen wide adoption, but I expect that with its prominent integration into the module system, its use will increase considerably. To make sure you know your way around its API, we explore it in this section.