ServiceLoader

public final class ServiceLoader
extends Object implements Iterable<S>

java.lang.Object
   ↳ java.util.ServiceLoader<S>


A facility to load implementations of a service.

A service is a well-known interface or class for which zero, one, or many service providers exist. A service provider (or just provider) is a class that implements or subclasses the well-known interface or class. A ServiceLoader is an object that locates and loads service providers deployed in the run time environment at a time of an application's choosing. Application code refers only to the service, not to service providers, and is assumed to be capable of choosing between multiple service providers (based on the functionality they expose through the service), and handling the possibility that no service providers are located.

Obtaining a service loader

An application obtains a service loader for a given service by invoking one of the static load methods of ServiceLoader.

Nested classes

interface ServiceLoader.Provider<S>

Represents a service provider located by ServiceLoader

Public methods

Optional<S> findFirst()

Load the first available service provider of this loader's service.

Iterator<S> iterator()

Returns an iterator to lazily load and instantiate the available providers of this loader's service.

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.

static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader)

Creates a new service loader for the given service.

static <S> ServiceLoader<S> loadInstalled(Class<S> service)

Creates a new service loader for the given service type, using the extension class loader.

void reload()

Clear this loader's provider cache so that all providers will be reloaded.

Stream<Provider<S>> stream()

Returns a stream to lazily load available providers of this loader's service.

String toString()

Returns a string describing this service.

Inherited methods

Public methods

findFirst

Added in API level 34
public Optional<S> findFirst ()

Load the first available service 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 service provider. If no service providers are located then it uses a default implementation.

CodecFactory factory = ServiceLoader.load(CodecFactory.class)
                                        .findFirst()
                                        .orElse(DEFAULT_CODECSET_FACTORY);
 

Returns
Optional<S> The first service provider or empty Optional if no service providers are located

Throws
ServiceConfigurationError If a provider class cannot be loaded for any of the reasons specified in the Errors section above.

iterator

Added in API level 9
public Iterator<S> iterator ()

Returns an iterator to lazily load and instantiate the available providers of this loader's service.

To achieve laziness the actual work of locating and instantiating providers is done by the iterator itself. Its hasNext and next methods can therefore throw a ServiceConfigurationError for any of the reasons specified in the Errors section above. To write robust code it is only necessary to catch ServiceConfigurationError when using the iterator. If 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.

Caching: 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 service providers, adding each one to the cache in turn. 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.

API 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.
Returns
Iterator<S> An iterator that lazily loads providers for this loader's service

load

Added in API level 9
public static 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.
Parameters
service Class: The interface or abstract class representing the service

Returns
ServiceLoader<S> A new service loader

Throws
ServiceConfigurationError if the service type is not accessible to the caller

load

Added in API level 9
public static ServiceLoader<S> load (Class<S> service, 
                ClassLoader loader)

Creates a new service loader for the given service. The service loader uses the given class loader as the starting point to locate service providers for the service.

API Note:
  • If the class path of the class loader includes remote network URLs then those URLs may 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.

Parameters
service Class: The interface or abstract class representing the service

loader ClassLoader: 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
ServiceLoader<S> A new service loader

Throws
ServiceConfigurationError if the service type is not accessible to the caller