What is a service?
Identifying service provider
Contents of provider1/META-INF/services/java.sql.Driver:
drivers.DriverOne #This is driver one #Next is driver two drivers.DriverTwo
Contents of provider2/META-INF/services/java.sql.Driver:
The next step would be to make the ClassLoader load the configuration files. First priority would be let the thread context’s class loader load the resources. If there is no classloader stashed at thread’s context, it will be delegated to system’s classloader. Read more about the hierarchy of classloaders here.
In our example, we add directories provider1 and provider2 to the classpath so that the classloader can locate these resources.
There is already one java.sql.Driver configuration file in jdk1.7.0_11/jre/lib/resources.jar so the classloader ends up locating three configuration files.
ServiceLoader.load(Driver.class), it creates a cache for providers and an iterator which will lazily instantiate the Driver implementations as we iterate through the resources.
Iterating through services
As we iterate through each resource, the configuration file will be read. Each line in the configuration file will have one fully-qualified class name which will be used to load and instantiate. The instantiated provider class will be cached for future iterations.