Module java.base
Package java.util

Class ServiceLoader<S>

  • Type Parameters:
    S - The type of the service to be loaded by this loader
    All Implemented Interfaces:
    Iterable<S>


    public final class ServiceLoader<S>
    extends Object
    implements Iterable<S>
    A simple service-provider loading facility.

    A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Providers may be developed and deployed as modules and made available using the application module path. Providers may alternatively be packaged as JAR files and made available by adding them to the application class path. The advantage of developing a provider as a module is that the provider can be fully encapsulated to hide all details of its implementation.

    For the purpose of loading, a service is represented by a single type, that is, a single interface or abstract class. (A concrete class can be used, but this is not recommended.) A provider of a given service contains one or more concrete classes that extend this service type with data and code specific to the provider. The provider class is typically not the entire provider itself but rather a proxy which contains enough information to decide whether the provider is able to satisfy a particular request together with code that can create the actual provider on demand. The details of provider classes tend to be highly service-specific; no single class or interface could possibly unify them, so no such type is defined here.

    Providers deployed as explicit modules on the module path are instantiated by a provider factory or directly via the provider's constructor. In the module declaration then the class name specified in the provides clause is a provider factory if it is public and defines a public static no-args method named "provider". The return type of the method must be assignable to the service type. If the class is not a provider factory then it is public with a public zero-argument constructor. The requirement that the provider factory or provider class be public helps to document the intent that the provider will be instantiated by the service-provider loading facility.

    As an example, suppose a module declares the following:

    
         provides com.example.CodecSet with com.example.impl.StandardCodecs;
         provides com.example.CodecSet with com.example.impl.ExtendedCodecsFactory;
     

    where com.example.CodecSet is the service type, com.example.impl.StandardCodecs is a provider class that is public with a public no-args constructor, com.example.impl.ExtendedCodecsFactory is a public class that defines a public static no-args method named "provider" with a return type that is CodecSet or a subtype of. For this example then StandardCodecs's no-arg constructor will be used to instantiate StandardCodecs. ExtendedCodecsFactory will be treated as a provider factory and ExtendedCodecsFactory.provider() will be invoked to obtain the provider.

    Providers deployed on the class path or as automatic-modules on the module path must have a public zero-argument constructor.

    An application or library using this loading facility and developed and deployed as an explicit module must have an appropriate uses clause in its module descriptor to declare that the module uses implementations of the service. A corresponding requirement is that a provider deployed as an explicit module must have an appropriate provides clause in its module descriptor to declare that the module provides an implementation of the service. The uses and provides allow consumers of a service to be linked to modules containing providers of the service.

    A service provider that is packaged as a JAR file for the class path is identified by placing a provider-configuration file in the resource directory META-INF/services. The file's name is the fully-qualified binary name of the service's type. The file contains a list of fully-qualified binary names of concrete provider classes, one per line. Space and tab characters surrounding each name, as well as blank lines, are ignored. The comment character is '#' ('\u0023', NUMBER SIGN); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8. If a particular concrete provider class is named in more than one configuration file, or is named in the same configuration file more than once, then the duplicates are ignored. The configuration file naming a particular provider need not be in the same JAR file or other distribution unit as the provider itself. The provider must be visible from the same class loader that was initially queried to locate the configuration file; note that this is not necessarily the class loader from which the file was actually loaded.

    Providers are located and instantiated lazily, that is, on demand. A service loader maintains a cache of the providers that have been loaded so far. Each invocation of the iterator method returns an iterator that first yields all of the elements cached from previous iteration, in instantiation order, and then lazily locates and instantiates any remaining providers, adding each one to the cache in turn. Similarly, each invocation of the stream method returns a stream that first processes all providers loaded by previous stream operations, in load order, and then lazily locates any remaining providers. Caches are cleared via the reload method.

    Locating providers

    The load methods locate providers using a class loader or module layer. When locating providers using a class loader then providers in both named and unnamed modules may be located. When locating providers using a module layer then only providers in named modules in the layer (or parent layers) are located.

    When locating providers using a class loader then any providers in named modules defined to the class loader, or any class loader that is reachable via parent delegation, are located. Additionally, providers in module layers other than the boot layer, where the module layer contains modules defined to the class loader, or any class loader reachable via parent delegation, are also located. For example, suppose there is a module layer where each module is defined to its own class loader (see defineModulesWithManyLoaders). If the load method is invoked to locate providers using any of these class loaders for this layer then it will locate all of the providers in that layer, irrespective of their defining class loader.

    In the case of unnamed modules then the service configuration files are located using the class loader's ClassLoader.getResources(String) method. Any providers listed should be visible via the class loader specified to the load method. If a provider in a named module is listed then it is ignored - this is to avoid duplicates that would otherwise arise when a module has both a provides clause and a service configuration file in META-INF/services that lists the same provider.

    Ordering

    Service loaders created to locate providers using a ClassLoader locate providers as follows:

    • Providers in named modules are located before providers on the class path (or more generally, unnamed modules).
    • When locating providers in named modules then the service loader will locate providers in modules defined to the class loader, then its parent class loader, its parent parent, and so on to the bootstrap class loader. If a ClassLoader, or any class loader in the parent delegation chain, defines modules in a custom module ModuleLayer then all providers in that layer are located, irrespective of their class loader. The ordering of modules defined to the same class loader, or the ordering of modules in a layer, is not defined.
    • If a named module declares more than one provider then the providers are located in the iteration order of the providers list. Providers added dynamically by instrumentation agents (redefineModule) are always located after providers declared by the module.
    • When locating providers in unnamed modules then the ordering is based on the order that the class loader's ClassLoader.getResources(String) method finds the service configuration files.

    Service loaders created to locate providers in a module layer will first locate providers in the layer, before locating providers in parent layers. Traversal of parent layers is depth-first with each layer visited at most once. For example, suppose L0 is the boot layer, L1 and L2 are custom layers with L0 as their parent. Now suppose that L3 is created with L1 and L2 as the parents (in that order). Using a service loader to locate providers with L3 as the content will locate providers in the following order: L3, L1, L0, L2. The ordering of modules in a layer is not defined.

    Selection and filtering

    Selecting a provider or filtering providers will usually involve invoking a provider method. Where selection or filtering based on the provider class is needed then it can be done using a stream. For example, the following collects the providers that have a specific annotation:

    
         Set<CodecSet> providers = ServiceLoader.load(CodecSet.class)
                .stream()
                .filter(p -> p.type().isAnnotationPresent(Managed.class))
                .map(Provider::get)
                .collect(Collectors.toSet());
     

    Security

    Service loaders always execute in the security context of the caller of the iterator or stream methods and may also be restricted by the security context of the caller that created the service loader. Trusted system code should typically invoke the methods in this class, and the methods of the iterators which they return, from within a privileged security context.

    Concurrency

    Instances of this class are not safe for use by multiple concurrent threads.

    Null handling

    Unless otherwise specified, passing a null argument to any method in this class will cause a NullPointerException to be thrown.

    Example

    Suppose we have a service type com.example.CodecSet which is intended to represent sets of encoder/decoder pairs for some protocol. In this case it is an abstract class with two abstract methods:

     public abstract Encoder getEncoder(String encodingName);
     public abstract Decoder getDecoder(String encodingName);
    Each method returns an appropriate object or null if the provider does not support the given encoding. Typical providers support more than one encoding.

    The CodecSet class creates and saves a single service instance at initialization:

    
     private static ServiceLoader<CodecSet> codecSetLoader
         = ServiceLoader.load(CodecSet.class);
     

    To locate an encoder for a given encoding name it defines a static factory method which iterates through the known and available providers, returning only when it has located a suitable encoder or has run out of providers.

    
     public static Encoder getEncoder(String encodingName) {
         for (CodecSet cp : codecSetLoader) {
             Encoder enc = cp.getEncoder(encodingName);
             if (enc != null)
                 return enc;
         }
         return null;
     }

    A getDecoder method is defined similarly.

    If the code creating and using the service loader is developed as a module then its module descriptor will declare the usage with:

    uses com.example.CodecSet;

    Now suppose that com.example.impl.StandardCodecs is an implementation of the CodecSet service and developed as a module. In that case then the module with the service provider module will declare this in its module descriptor:

    provides com.example.CodecSet with com.example.impl.StandardCodecs;
     

    On the other hand, suppose com.example.impl.StandardCodecs is packaged in a JAR file for the class path then the JAR file will contain a file named:

    META-INF/services/com.example.CodecSet
    that contains the single line:
    com.example.impl.StandardCodecs    # Standard codecs

    Usage Note If the class path of a class loader that is used for provider loading includes remote network URLs then those URLs will be dereferenced in the process of searching for provider-configuration files.

    This activity is normal, although it may cause puzzling entries to be created in web-server logs. If a web server is not configured correctly, however, then this activity may cause the provider-loading algorithm to fail spuriously.

    A web server should return an HTTP 404 (Not Found) response when a requested resource does not exist. Sometimes, however, web servers are erroneously configured to return an HTTP 200 (OK) response along with a helpful HTML error page in such cases. This will cause a ServiceConfigurationError to be thrown when this class attempts to parse the HTML page as a provider-configuration file. The best solution to this problem is to fix the misconfigured web server to return the correct response code (HTTP 404) along with the HTML error page.

    Since:
    1.6
    • Method Detail

      • iterator

        public Iterator<S> iterator​()
        Lazily load and instantiate the available providers of this loader's service.

        The iterator returned by this method first yields all of the elements of the provider cache, in the order that they were loaded. It then lazily loads and instantiates any remaining providers, adding each one to the cache in turn.

        To achieve laziness the actual work of locating and instantiating providers must be done by the iterator itself. Its hasNext and next methods can therefore throw a ServiceConfigurationError if a provider class cannot be loaded, doesn't have an appropriate static factory method or constructor, can't be assigned to the service type or if any other kind of exception or error is thrown as the next provider is located and instantiated. To write robust code it is only necessary to catch ServiceConfigurationError when using a service iterator.

        If such an error is thrown then subsequent invocations of the iterator will make a best effort to locate and instantiate the next available provider, but in general such recovery cannot be guaranteed.

        Design Note Throwing an error in these cases may seem extreme. The rationale for this behavior is that a malformed provider-configuration file, like a malformed class file, indicates a serious problem with the way the Java virtual machine is configured or is being used. As such it is preferable to throw an error rather than try to recover or, even worse, fail silently.

        If this loader's provider caches are cleared by invoking the reload method then existing iterators for this service loader should be discarded. The hasNext and next methods of the iterator throw ConcurrentModificationException if used after the provider cache has been cleared.

        The iterator returned by this method does not support removal. Invoking its remove method will cause an UnsupportedOperationException to be thrown.

        Specified by:
        iterator in interface Iterable<S>
        Returns:
        An iterator that lazily loads providers for this loader's service
      • stream

        public Stream<ServiceLoader.Provider<S>> stream​()
        Returns a stream that lazily loads the available providers of this loader's service. The stream elements are of type Provider, the Provider's get method must be invoked to get or instantiate the provider.

        When processing the stream then providers that were previously loaded by stream operations are processed first, in load order. It then lazily loads any remaining providers. If a provider class cannot be loaded, can't be assigned to the service type, or some other error is thrown when locating the provider then it is wrapped with a ServiceConfigurationError and thrown by whatever method caused the provider to be loaded.

        If this loader's provider caches are cleared by invoking the reload method then existing streams for this service loader should be discarded. The returned stream's source Spliterator is fail-fast and will throw ConcurrentModificationException if the provider cache has been cleared.

        The following examples demonstrate usage. The first example creates a stream of providers, the second example is the same except that it sorts the providers by provider class name (and so locate all providers).

        
            Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
                    .stream()
                    .map(Provider::get);
        
            Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
                    .stream()
                    .sorted(Comparator.comparing(p -> p.type().getName()))
                    .map(Provider::get);
         
        Returns:
        A stream that lazily loads providers for this loader's service
        Since:
        9
      • load

        public static <S> ServiceLoader<S> load​(Class<S> service,
                                                ClassLoader loader)
        Creates a new service loader for the given service type and class loader.
        Type Parameters:
        S - the class of the service type
        Parameters:
        service - The interface or abstract class representing the service
        loader - The class loader to be used to load provider-configuration files and provider classes, or null if the system class loader (or, failing that, the bootstrap class loader) is to be used
        Returns:
        A new service loader
        Throws:
        ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service
      • load

        public static <S> ServiceLoader<S> load​(Class<S> service)
        Creates a new service loader for the given service type, using the current thread's context class loader.

        An invocation of this convenience method of the form

        
         ServiceLoader.load(service)
         
        is equivalent to
        
         ServiceLoader.load(service, Thread.currentThread().getContextClassLoader())
         
        API Note:
        Service loader objects obtained with this method should not be cached VM-wide. For example, different applications in the same VM may have different thread context class loaders. A lookup by one application may locate a service provider that is only visible via its thread context class loader and so is not suitable to be located by the other application. Memory leaks can also arise. A thread local may be suited to some applications.
        Type Parameters:
        S - the class of the service type
        Parameters:
        service - The interface or abstract class representing the service
        Returns:
        A new service loader
        Throws:
        ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service
      • loadInstalled

        public static <S> ServiceLoader<S> loadInstalled​(Class<S> service)
        Creates a new service loader for the given service type, using the platform class loader.

        This convenience method is equivalent to:

        
         ServiceLoader.load(service, ClassLoader.getPlatformClassLoader())
         

        This method is intended for use when only installed providers are desired. The resulting service will only find and load providers that have been installed into the current Java virtual machine; providers on the application's module path or class path will be ignored.

        Type Parameters:
        S - the class of the service type
        Parameters:
        service - The interface or abstract class representing the service
        Returns:
        A new service loader
        Throws:
        ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service
      • load

        public static <S> ServiceLoader<S> load​(ModuleLayer layer,
                                                Class<S> service)
        Creates a new service loader for the given service type that loads service providers from modules in the given ModuleLayer and its ancestors.
        API Note:
        Unlike the other load methods defined here, the service type is the second parameter. The reason for this is to avoid source compatibility issues for code that uses load(S, null).
        Type Parameters:
        S - the class of the service type
        Parameters:
        layer - The module layer
        service - The interface or abstract class representing the service
        Returns:
        A new service loader
        Throws:
        ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service
        Since:
        9
      • findFirst

        public Optional<S> findFirst​()
        Load the first available provider of this loader's service. This convenience method is equivalent to invoking the iterator() method and obtaining the first element. It therefore returns the first element from the provider cache if possible, it otherwise attempts to load and instantiate the first provider.

        The following example loads the first available provider. If there are no providers deployed then it uses a default implementation.

        
            CodecSet provider =
                ServiceLoader.load(CodecSet.class).findFirst().orElse(DEFAULT_CODECSET);
         
        Returns:
        The first provider or empty Optional if no providers are located
        Throws:
        ServiceConfigurationError - If a provider class cannot be loaded, doesn't have the appropriate static factory method or constructor, can't be assigned to the service type, or if any other kind of exception or error is thrown when locating or instantiating the provider.
        Since:
        9
      • reload

        public void reload​()
        Clear this loader's provider cache so that all providers will be reloaded.

        After invoking this method, subsequent invocations of the iterator or stream methods will lazily look up providers (and instantiate in the case of iterator) from scratch, just as is done by a newly-created loader.

        This method is intended for use in situations in which new providers can be installed into a running Java virtual machine.

      • toString

        public String toString​()
        Returns a string describing this service.
        Overrides:
        toString in class Object
        Returns:
        A descriptive string