< prev index next >

src/java.base/share/classes/java/util/ServiceLoader.java

Print this page




 102  * }</pre>
 103  *
 104  * <p> where {@code com.example.CodecSet} is the service type, {@code
 105  * com.example.impl.StandardCodecs} is a provider class that is public with a
 106  * public no-args constructor, {@code com.example.impl.ExtendedCodecsFactory}
 107  * is a public class that defines a public static no-args method named
 108  * "{@code provider}" with a return type that is {@code CodecSet} or a subtype
 109  * of. For this example then {@code StandardCodecs}'s no-arg constructor will
 110  * be used to instantiate {@code StandardCodecs}. {@code ExtendedCodecsFactory}
 111  * will be treated as a provider factory and {@code
 112  * ExtendedCodecsFactory.provider()} will be invoked to obtain the provider.
 113  *
 114  * <p> Providers deployed on the class path or as {@link
 115  * java.lang.module.ModuleDescriptor#isAutomatic automatic-modules} on the
 116  * module path must have a public zero-argument constructor.
 117  *
 118  * <p> An application or library using this loading facility and developed
 119  * and deployed as an explicit module must have an appropriate <i>uses</i>
 120  * clause in its <i>module descriptor</i> to declare that the module uses
 121  * implementations of the service. A corresponding requirement is that a
 122  * provider deployed as a named module must have an appropriate
 123  * <i>provides</i> clause in its module descriptor to declare that the module
 124  * provides an implementation of the service. The <i>uses</i> and
 125  * <i>provides</i> allow consumers of a service to be <i>linked</i> to modules
 126  * containing providers of the service.
 127  *
 128  * <p> A service provider that is packaged as a JAR file for the class path is
 129  * identified by placing a <i>provider-configuration file</i> in the resource
 130  * directory <tt>META-INF/services</tt>. The file's name is the fully-qualified
 131  * <a href="../lang/ClassLoader.html#name">binary name</a> of the service's
 132  * type. The file contains a list of fully-qualified binary names of concrete
 133  * provider classes, one per line.  Space and tab characters surrounding each
 134  * name, as well as blank lines, are ignored.  The comment character is
 135  * <tt>'#'</tt> (<tt>'\u0023'</tt>,
 136  * <font style="font-size:smaller;">NUMBER SIGN</font>); on
 137  * each line all characters following the first comment character are ignored.
 138  * The file must be encoded in UTF-8.
 139  * If a particular concrete provider class is named in more than one
 140  * configuration file, or is named in the same configuration file more than
 141  * once, then the duplicates are ignored.  The configuration file naming a
 142  * particular provider need not be in the same JAR file or other distribution


 186  * META-INF/services} that lists the same provider.
 187  *
 188  * <h2> Ordering </h2>
 189  *
 190  * <p> Service loaders created to locate providers using a {@code ClassLoader}
 191  * locate providers as follows:
 192  * <ul>
 193  *     <li> Providers in named modules are located before providers on the
 194  *     class path (or more generally, unnamed modules). </li>
 195  *
 196  *     <li> When locating providers in named modules then the service loader
 197  *     will locate providers in modules defined to the class loader, then its
 198  *     parent class loader, its parent parent, and so on to the bootstrap class
 199  *     loader. If a {@code ClassLoader}, or any class loader in the parent
 200  *     delegation chain, defines modules in a custom module {@link Layer} then
 201  *     all providers in that layer are located, irrespective of their class
 202  *     loader. The ordering of modules defined to the same class loader, or the
 203  *     ordering of modules in a layer, is not defined. </li>
 204  *
 205  *     <li> If a named module declares more than one provider then the providers
 206  *     are located in the order that they appear in the {@code provides} table of
 207  *     the {@code Module} class file attribute ({@code module-info.class}). </li>



 208  *
 209  *     <li> When locating providers in unnamed modules then the ordering is
 210  *     based on the order that the class loader's {@link
 211  *     ClassLoader#getResources(String) ClassLoader.getResources(String)}
 212  *     method finds the service configuration files. </li>
 213  * </ul>
 214  *
 215  * <p> Service loaders created to locate providers in a module {@link Layer}
 216  * will first locate providers in the layer, before locating providers in
 217  * parent layers. Traversal of parent layers is depth-first with each layer
 218  * visited at most once. For example, suppose L0 is the boot layer, L1 and
 219  * L2 are custom layers with L0 as their parent. Now suppose that L3 is
 220  * created with L1 and L2 as the parents (in that order). Using a service
 221  * loader to locate providers with L3 as the content will locate providers
 222  * in the following order: L3, L1, L0, L2. The ordering of modules in a layer
 223  * is not defined.
 224  *
 225  * <h2> Selection and filtering </h2>
 226  *
 227  * <p> Selecting a provider or filtering providers will usually involve invoking


 318  *
 319  * <p> This activity is normal, although it may cause puzzling entries to be
 320  * created in web-server logs.  If a web server is not configured correctly,
 321  * however, then this activity may cause the provider-loading algorithm to fail
 322  * spuriously.
 323  *
 324  * <p> A web server should return an HTTP 404 (Not Found) response when a
 325  * requested resource does not exist.  Sometimes, however, web servers are
 326  * erroneously configured to return an HTTP 200 (OK) response along with a
 327  * helpful HTML error page in such cases.  This will cause a {@link
 328  * ServiceConfigurationError} to be thrown when this class attempts to parse
 329  * the HTML page as a provider-configuration file.  The best solution to this
 330  * problem is to fix the misconfigured web server to return the correct
 331  * response code (HTTP 404) along with the HTML error page.
 332  *
 333  * @param  <S>
 334  *         The type of the service to be loaded by this loader
 335  *
 336  * @author Mark Reinhold
 337  * @since 1.6


 338  */
 339 
 340 public final class ServiceLoader<S>
 341     implements Iterable<S>
 342 {
 343     // The class or interface representing the service being loaded
 344     private final Class<S> service;
 345 
 346     // The class of the service type
 347     private final String serviceName;
 348 
 349     // The module Layer used to locate providers; null when locating
 350     // providers using a class loader
 351     private final Layer layer;
 352 
 353     // The class loader used to locate, load, and instantiate providers;
 354     // null when locating provider using a module Layer
 355     private final ClassLoader loader;
 356 
 357     // The access control context taken when the ServiceLoader is created


 369     // Incremented when reload is called
 370     private int reloadCount;
 371 
 372     private static JavaLangAccess LANG_ACCESS;
 373     private static JavaLangReflectModuleAccess JLRM_ACCESS;
 374     static {
 375         LANG_ACCESS = SharedSecrets.getJavaLangAccess();
 376         JLRM_ACCESS = SharedSecrets.getJavaLangReflectModuleAccess();
 377     }
 378 
 379     /**
 380      * Represents a service provider located by {@code ServiceLoader}.
 381      *
 382      * <p> When using a loader's {@link ServiceLoader#stream() stream()} method
 383      * then the elements are of type {@code Provider}. This allows processing
 384      * to select or filter on the provider class without instantiating the
 385      * provider. </p>
 386      *
 387      * @param  <S> The service type
 388      * @since 9

 389      */
 390     public static interface Provider<S> extends Supplier<S> {
 391         /**
 392          * Returns the provider type. There is no guarantee that this type is
 393          * accessible or that it has a public no-args constructor. The {@link
 394          * #get() get()} method should be used to obtain the provider instance.
 395          *
 396          * <p> When a module declares that the provider class is created by a
 397          * provider factory then this method returns the return type of its
 398          * public static "{@code provider()}" method.
 399          *
 400          * @return The provider type
 401          */
 402         Class<? extends S> type();
 403 
 404         /**
 405          * Returns an instance of the provider.
 406          *
 407          * @return An instance of the provider.
 408          *


 910          */
 911         private List<ServiceProvider> providers(Layer layer) {
 912             ServicesCatalog catalog = JLRM_ACCESS.getServicesCatalog(layer);
 913             return catalog.findServices(serviceName);
 914         }
 915 
 916         /**
 917          * Returns an iterator to iterate over the implementations of {@code
 918          * service} in modules defined to the given class loader or in custom
 919          * layers with a module defined to this class loader.
 920          */
 921         private Iterator<ServiceProvider> iteratorFor(ClassLoader loader) {
 922 
 923             // modules defined to this class loader
 924             ServicesCatalog catalog;
 925             if (loader == null) {
 926                 catalog = BootLoader.getServicesCatalog();
 927             } else {
 928                 catalog = ServicesCatalog.getServicesCatalogOrNull(loader);
 929             }
 930             Stream<ServiceProvider> stream1;
 931             if (catalog == null) {
 932                 stream1 = Stream.empty();
 933             } else {
 934                 stream1 = catalog.findServices(serviceName).stream();
 935             }
 936 
 937             // modules in custom layers that define modules to the class loader
 938             Stream<ServiceProvider> stream2;
 939             if (loader == null) {
 940                 stream2 = Stream.empty();
 941             } else {

 942                 Layer bootLayer = Layer.boot();
 943                 stream2 = JLRM_ACCESS.layers(loader)
 944                         .filter(l -> (l != bootLayer))
 945                         .map(l -> providers(l))
 946                         .flatMap(List::stream);




 947             }
 948 
 949             return Stream.concat(stream1, stream2).iterator();
 950         }
 951 
 952         @Override
 953         public boolean hasNext() {
 954             // already have the next provider cached
 955             if (next != null)
 956                 return true;
 957 
 958             while (true) {
 959                 if (iterator.hasNext()) {
 960                     next = iterator.next();
 961                     return true;
 962                 }
 963 
 964                 // move to the next class loader if possible
 965                 if (currentLoader == null) {
 966                     return false;
 967                 } else {
 968                     currentLoader = currentLoader.getParent();
 969                     iterator = iteratorFor(currentLoader);


1197      * this behavior is that a malformed provider-configuration file, like a
1198      * malformed class file, indicates a serious problem with the way the Java
1199      * virtual machine is configured or is being used.  As such it is
1200      * preferable to throw an error rather than try to recover or, even worse,
1201      * fail silently.</blockquote>
1202      *
1203      * <p> If this loader's provider caches are cleared by invoking the {@link
1204      * #reload() reload} method then existing iterators for this service
1205      * loader should be discarded.
1206      * The {@link java.util.Iterator#hasNext() hasNext} and {@link
1207      * java.util.Iterator#next() next} methods of the iterator throw {@link
1208      * java.util.ConcurrentModificationException ConcurrentModificationException}
1209      * if used after the provider cache has been cleared.
1210      *
1211      * <p> The iterator returned by this method does not support removal.
1212      * Invoking its {@link java.util.Iterator#remove() remove} method will
1213      * cause an {@link UnsupportedOperationException} to be thrown.
1214      *
1215      * @return  An iterator that lazily loads providers for this loader's
1216      *          service



1217      */
1218     public Iterator<S> iterator() {
1219 
1220         // create lookup iterator if needed
1221         if (lookupIterator1 == null) {
1222             lookupIterator1 = newLookupIterator();
1223         }
1224 
1225         return new Iterator<S>() {
1226 
1227             // record reload count
1228             final int expectedReloadCount = ServiceLoader.this.reloadCount;
1229 
1230             // index into the cached providers list
1231             int index;
1232 
1233             /**
1234              * Throws ConcurrentModificationException if the list of cached
1235              * providers has been cleared by reload.
1236              */


1262             }
1263 
1264         };
1265     }
1266 
1267     /**
1268      * Returns a stream that lazily loads the available providers of this
1269      * loader's service. The stream elements are of type {@link Provider
1270      * Provider}, the {@code Provider}'s {@link Provider#get() get} method
1271      * must be invoked to get or instantiate the provider.
1272      *
1273      * <p> When processing the stream then providers that were previously
1274      * loaded by stream operations are processed first, in load order. It then
1275      * lazily loads any remaining providers. If a provider class cannot be
1276      * loaded, can't be assigned to the service type, or some other error is
1277      * thrown when locating the provider then it is wrapped with a {@code
1278      * ServiceConfigurationError} and thrown by whatever method caused the
1279      * provider to be loaded. </p>
1280      *
1281      * <p> If this loader's provider caches are cleared by invoking the {@link
1282      * #reload() reload} method then existing streams for this service
1283      * loader should be discarded. </p>


1284      *
1285      * <p> The following examples demonstrate usage. The first example
1286      * creates a stream of providers, the second example is the same except
1287      * that it sorts the providers by provider class name (and so locate all
1288      * providers).
1289      * <pre>{@code
1290      *    Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
1291      *            .stream()
1292      *            .map(Provider::get);
1293      *
1294      *    Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
1295      *            .stream()
1296      *            .sorted(Comparator.comparing(p -> p.type().getName()))
1297      *            .map(Provider::get);
1298      * }</pre>
1299      *
1300      * @return  A stream that lazily loads providers for this loader's service
1301      *
1302      * @since 9

1303      */
1304     public Stream<Provider<S>> stream() {
1305         // use cached providers as the source when all providers loaded
1306         if (loadedAllProviders) {
1307             return loadedProviders.stream();
1308         }
1309 
1310         // create lookup iterator if needed
1311         if (lookupIterator2 == null) {
1312             lookupIterator2 = newLookupIterator();
1313         }
1314 
1315         // use lookup iterator and cached providers as source
1316         Spliterator<Provider<S>> s = new ProviderSpliterator<>(lookupIterator2);
1317         return StreamSupport.stream(s, false);
1318     }
1319 
1320     private class ProviderSpliterator<T> implements Spliterator<Provider<T>> {
1321         final int expectedReloadCount = ServiceLoader.this.reloadCount;
1322         final Iterator<Provider<T>> iterator;


1397      * Creates a new service loader for the given service type and class
1398      * loader.
1399      *
1400      * @param  <S> the class of the service type
1401      *
1402      * @param  service
1403      *         The interface or abstract class representing the service
1404      *
1405      * @param  loader
1406      *         The class loader to be used to load provider-configuration files
1407      *         and provider classes, or {@code null} if the system class
1408      *         loader (or, failing that, the bootstrap class loader) is to be
1409      *         used
1410      *
1411      * @return A new service loader
1412      *
1413      * @throws ServiceConfigurationError
1414      *         if the service type is not accessible to the caller or the
1415      *         caller is in an explicit module and its module descriptor does
1416      *         not declare that it uses {@code service}



1417      */
1418     @CallerSensitive
1419     public static <S> ServiceLoader<S> load(Class<S> service,
1420                                             ClassLoader loader)
1421     {
1422         return new ServiceLoader<>(Reflection.getCallerClass(), service, loader);
1423     }
1424 
1425     /**
1426      * Creates a new service loader for the given service type, using the
1427      * current thread's {@linkplain java.lang.Thread#getContextClassLoader
1428      * context class loader}.
1429      *
1430      * <p> An invocation of this convenience method of the form
1431      * <pre>{@code
1432      * ServiceLoader.load(service)
1433      * }</pre>
1434      *
1435      * is equivalent to
1436      *


1440      *
1441      * @apiNote Service loader objects obtained with this method should not be
1442      * cached VM-wide. For example, different applications in the same VM may
1443      * have different thread context class loaders. A lookup by one application
1444      * may locate a service provider that is only visible via its thread
1445      * context class loader and so is not suitable to be located by the other
1446      * application. Memory leaks can also arise. A thread local may be suited
1447      * to some applications.
1448      *
1449      * @param  <S> the class of the service type
1450      *
1451      * @param  service
1452      *         The interface or abstract class representing the service
1453      *
1454      * @return A new service loader
1455      *
1456      * @throws ServiceConfigurationError
1457      *         if the service type is not accessible to the caller or the
1458      *         caller is in an explicit module and its module descriptor does
1459      *         not declare that it uses {@code service}



1460      */
1461     @CallerSensitive
1462     public static <S> ServiceLoader<S> load(Class<S> service) {
1463         ClassLoader cl = Thread.currentThread().getContextClassLoader();
1464         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1465     }
1466 
1467     /**
1468      * Creates a new service loader for the given service type, using the
1469      * {@linkplain ClassLoader#getPlatformClassLoader() platform class loader}.
1470      *
1471      * <p> This convenience method is equivalent to: </p>
1472      *
1473      * <pre>{@code
1474      * ServiceLoader.load(service, ClassLoader.getPlatformClassLoader())
1475      * }</pre>
1476      *
1477      * <p> This method is intended for use when only installed providers are
1478      * desired.  The resulting service will only find and load providers that
1479      * have been installed into the current Java virtual machine; providers on
1480      * the application's module path or class path will be ignored.
1481      *
1482      * @param  <S> the class of the service type
1483      *
1484      * @param  service
1485      *         The interface or abstract class representing the service
1486      *
1487      * @return A new service loader
1488      *
1489      * @throws ServiceConfigurationError
1490      *         if the service type is not accessible to the caller or the
1491      *         caller is in an explicit module and its module descriptor does
1492      *         not declare that it uses {@code service}



1493      */
1494     @CallerSensitive
1495     public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
1496         ClassLoader cl = ClassLoader.getPlatformClassLoader();
1497         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1498     }
1499 
1500     /**
1501      * Creates a new service loader for the given service type that loads
1502      * service providers from modules in the given {@code Layer} and its
1503      * ancestors.
1504      *
1505      * @apiNote Unlike the other load methods defined here, the service type
1506      * is the second parameter. The reason for this is to avoid source
1507      * compatibility issues for code that uses {@code load(S, null)}.
1508      *
1509      * @param  <S> the class of the service type
1510      *
1511      * @param  layer
1512      *         The module Layer
1513      *
1514      * @param  service
1515      *         The interface or abstract class representing the service
1516      *
1517      * @return A new service loader
1518      *
1519      * @throws ServiceConfigurationError
1520      *         if the service type is not accessible to the caller or the
1521      *         caller is in an explicit module and its module descriptor does
1522      *         not declare that it uses {@code service}
1523      *
1524      * @since 9

1525      */
1526     @CallerSensitive
1527     public static <S> ServiceLoader<S> load(Layer layer, Class<S> service) {
1528         return new ServiceLoader<>(Reflection.getCallerClass(), layer, service);
1529     }
1530 
1531     /**
1532      * Load the first available provider of this loader's service. This
1533      * convenience method is equivalent to invoking the {@link #iterator()
1534      * iterator()} method and obtaining the first element. It therefore
1535      * returns the first element from the provider cache if possible, it
1536      * otherwise attempts to load and instantiate the first provider.
1537      *
1538      * <p> The following example loads the first available provider. If there
1539      * are no providers deployed then it uses a default implementation.
1540      * <pre>{@code
1541      *    CodecSet provider =
1542      *        ServiceLoader.load(CodecSet.class).findFirst().orElse(DEFAULT_CODECSET);
1543      * }</pre>
1544      * @return The first provider or empty {@code Optional} if no providers
1545      *         are located
1546      *
1547      * @throws ServiceConfigurationError
1548      *         If a provider class cannot be loaded, doesn't have the
1549      *         appropriate static factory method or constructor, can't be
1550      *         assigned to the service type, or if any other kind of exception
1551      *         or error is thrown when locating or instantiating the provider.
1552      *
1553      * @since 9

1554      */
1555     public Optional<S> findFirst() {
1556         Iterator<S> iterator = iterator();
1557         if (iterator.hasNext()) {
1558             return Optional.of(iterator.next());
1559         } else {
1560             return Optional.empty();
1561         }
1562     }
1563 
1564     /**
1565      * Clear this loader's provider cache so that all providers will be
1566      * reloaded.
1567      *
1568      * <p> After invoking this method, subsequent invocations of the {@link
1569      * #iterator() iterator} or {@link #stream() stream} methods will lazily
1570      * look up providers (and instantiate in the case of {@code iterator})
1571      * from scratch, just as is done by a newly-created loader.
1572      *
1573      * <p> This method is intended for use in situations in which new providers




 102  * }</pre>
 103  *
 104  * <p> where {@code com.example.CodecSet} is the service type, {@code
 105  * com.example.impl.StandardCodecs} is a provider class that is public with a
 106  * public no-args constructor, {@code com.example.impl.ExtendedCodecsFactory}
 107  * is a public class that defines a public static no-args method named
 108  * "{@code provider}" with a return type that is {@code CodecSet} or a subtype
 109  * of. For this example then {@code StandardCodecs}'s no-arg constructor will
 110  * be used to instantiate {@code StandardCodecs}. {@code ExtendedCodecsFactory}
 111  * will be treated as a provider factory and {@code
 112  * ExtendedCodecsFactory.provider()} will be invoked to obtain the provider.
 113  *
 114  * <p> Providers deployed on the class path or as {@link
 115  * java.lang.module.ModuleDescriptor#isAutomatic automatic-modules} on the
 116  * module path must have a public zero-argument constructor.
 117  *
 118  * <p> An application or library using this loading facility and developed
 119  * and deployed as an explicit module must have an appropriate <i>uses</i>
 120  * clause in its <i>module descriptor</i> to declare that the module uses
 121  * implementations of the service. A corresponding requirement is that a
 122  * provider deployed as an explicit module must have an appropriate
 123  * <i>provides</i> clause in its module descriptor to declare that the module
 124  * provides an implementation of the service. The <i>uses</i> and
 125  * <i>provides</i> allow consumers of a service to be <i>linked</i> to modules
 126  * containing providers of the service.
 127  *
 128  * <p> A service provider that is packaged as a JAR file for the class path is
 129  * identified by placing a <i>provider-configuration file</i> in the resource
 130  * directory <tt>META-INF/services</tt>. The file's name is the fully-qualified
 131  * <a href="../lang/ClassLoader.html#name">binary name</a> of the service's
 132  * type. The file contains a list of fully-qualified binary names of concrete
 133  * provider classes, one per line.  Space and tab characters surrounding each
 134  * name, as well as blank lines, are ignored.  The comment character is
 135  * <tt>'#'</tt> (<tt>'\u0023'</tt>,
 136  * <font style="font-size:smaller;">NUMBER SIGN</font>); on
 137  * each line all characters following the first comment character are ignored.
 138  * The file must be encoded in UTF-8.
 139  * If a particular concrete provider class is named in more than one
 140  * configuration file, or is named in the same configuration file more than
 141  * once, then the duplicates are ignored.  The configuration file naming a
 142  * particular provider need not be in the same JAR file or other distribution


 186  * META-INF/services} that lists the same provider.
 187  *
 188  * <h2> Ordering </h2>
 189  *
 190  * <p> Service loaders created to locate providers using a {@code ClassLoader}
 191  * locate providers as follows:
 192  * <ul>
 193  *     <li> Providers in named modules are located before providers on the
 194  *     class path (or more generally, unnamed modules). </li>
 195  *
 196  *     <li> When locating providers in named modules then the service loader
 197  *     will locate providers in modules defined to the class loader, then its
 198  *     parent class loader, its parent parent, and so on to the bootstrap class
 199  *     loader. If a {@code ClassLoader}, or any class loader in the parent
 200  *     delegation chain, defines modules in a custom module {@link Layer} then
 201  *     all providers in that layer are located, irrespective of their class
 202  *     loader. The ordering of modules defined to the same class loader, or the
 203  *     ordering of modules in a layer, is not defined. </li>
 204  *
 205  *     <li> If a named module declares more than one provider then the providers
 206  *     are located in the iteration order of the {@link
 207  *     java.lang.module.ModuleDescriptor.Provides#providers() providers} list.
 208  *     Providers added dynamically by instrumentation agents ({@link
 209  *     java.lang.instrument.Instrumentation#redefineModule redefineModule})
 210  *     are always located after providers declared by the module. </li>
 211  *
 212  *     <li> When locating providers in unnamed modules then the ordering is
 213  *     based on the order that the class loader's {@link
 214  *     ClassLoader#getResources(String) ClassLoader.getResources(String)}
 215  *     method finds the service configuration files. </li>
 216  * </ul>
 217  *
 218  * <p> Service loaders created to locate providers in a module {@link Layer}
 219  * will first locate providers in the layer, before locating providers in
 220  * parent layers. Traversal of parent layers is depth-first with each layer
 221  * visited at most once. For example, suppose L0 is the boot layer, L1 and
 222  * L2 are custom layers with L0 as their parent. Now suppose that L3 is
 223  * created with L1 and L2 as the parents (in that order). Using a service
 224  * loader to locate providers with L3 as the content will locate providers
 225  * in the following order: L3, L1, L0, L2. The ordering of modules in a layer
 226  * is not defined.
 227  *
 228  * <h2> Selection and filtering </h2>
 229  *
 230  * <p> Selecting a provider or filtering providers will usually involve invoking


 321  *
 322  * <p> This activity is normal, although it may cause puzzling entries to be
 323  * created in web-server logs.  If a web server is not configured correctly,
 324  * however, then this activity may cause the provider-loading algorithm to fail
 325  * spuriously.
 326  *
 327  * <p> A web server should return an HTTP 404 (Not Found) response when a
 328  * requested resource does not exist.  Sometimes, however, web servers are
 329  * erroneously configured to return an HTTP 200 (OK) response along with a
 330  * helpful HTML error page in such cases.  This will cause a {@link
 331  * ServiceConfigurationError} to be thrown when this class attempts to parse
 332  * the HTML page as a provider-configuration file.  The best solution to this
 333  * problem is to fix the misconfigured web server to return the correct
 334  * response code (HTTP 404) along with the HTML error page.
 335  *
 336  * @param  <S>
 337  *         The type of the service to be loaded by this loader
 338  *
 339  * @author Mark Reinhold
 340  * @since 1.6
 341  * @revised 9
 342  * @spec JPMS
 343  */
 344 
 345 public final class ServiceLoader<S>
 346     implements Iterable<S>
 347 {
 348     // The class or interface representing the service being loaded
 349     private final Class<S> service;
 350 
 351     // The class of the service type
 352     private final String serviceName;
 353 
 354     // The module Layer used to locate providers; null when locating
 355     // providers using a class loader
 356     private final Layer layer;
 357 
 358     // The class loader used to locate, load, and instantiate providers;
 359     // null when locating provider using a module Layer
 360     private final ClassLoader loader;
 361 
 362     // The access control context taken when the ServiceLoader is created


 374     // Incremented when reload is called
 375     private int reloadCount;
 376 
 377     private static JavaLangAccess LANG_ACCESS;
 378     private static JavaLangReflectModuleAccess JLRM_ACCESS;
 379     static {
 380         LANG_ACCESS = SharedSecrets.getJavaLangAccess();
 381         JLRM_ACCESS = SharedSecrets.getJavaLangReflectModuleAccess();
 382     }
 383 
 384     /**
 385      * Represents a service provider located by {@code ServiceLoader}.
 386      *
 387      * <p> When using a loader's {@link ServiceLoader#stream() stream()} method
 388      * then the elements are of type {@code Provider}. This allows processing
 389      * to select or filter on the provider class without instantiating the
 390      * provider. </p>
 391      *
 392      * @param  <S> The service type
 393      * @since 9
 394      * @spec JPMS
 395      */
 396     public static interface Provider<S> extends Supplier<S> {
 397         /**
 398          * Returns the provider type. There is no guarantee that this type is
 399          * accessible or that it has a public no-args constructor. The {@link
 400          * #get() get()} method should be used to obtain the provider instance.
 401          *
 402          * <p> When a module declares that the provider class is created by a
 403          * provider factory then this method returns the return type of its
 404          * public static "{@code provider()}" method.
 405          *
 406          * @return The provider type
 407          */
 408         Class<? extends S> type();
 409 
 410         /**
 411          * Returns an instance of the provider.
 412          *
 413          * @return An instance of the provider.
 414          *


 916          */
 917         private List<ServiceProvider> providers(Layer layer) {
 918             ServicesCatalog catalog = JLRM_ACCESS.getServicesCatalog(layer);
 919             return catalog.findServices(serviceName);
 920         }
 921 
 922         /**
 923          * Returns an iterator to iterate over the implementations of {@code
 924          * service} in modules defined to the given class loader or in custom
 925          * layers with a module defined to this class loader.
 926          */
 927         private Iterator<ServiceProvider> iteratorFor(ClassLoader loader) {
 928 
 929             // modules defined to this class loader
 930             ServicesCatalog catalog;
 931             if (loader == null) {
 932                 catalog = BootLoader.getServicesCatalog();
 933             } else {
 934                 catalog = ServicesCatalog.getServicesCatalogOrNull(loader);
 935             }
 936             List<ServiceProvider> providers;
 937             if (catalog == null) {
 938                 providers = List.of();
 939             } else {
 940                 providers = catalog.findServices(serviceName);
 941             }
 942 
 943             // modules in custom layers that define modules to the class loader

 944             if (loader == null) {
 945                 return providers.iterator();
 946             } else {
 947                 List<ServiceProvider> allProviders = new ArrayList<>(providers);
 948                 Layer bootLayer = Layer.boot();
 949                 Iterator<Layer> iterator = JLRM_ACCESS.layers(loader).iterator();
 950                 while (iterator.hasNext()) {
 951                     Layer layer = iterator.next();
 952                     if (layer != bootLayer) {
 953                         allProviders.addAll(providers(layer));
 954                     }
 955                 }
 956                 return allProviders.iterator();
 957             }


 958         }
 959 
 960         @Override
 961         public boolean hasNext() {
 962             // already have the next provider cached
 963             if (next != null)
 964                 return true;
 965 
 966             while (true) {
 967                 if (iterator.hasNext()) {
 968                     next = iterator.next();
 969                     return true;
 970                 }
 971 
 972                 // move to the next class loader if possible
 973                 if (currentLoader == null) {
 974                     return false;
 975                 } else {
 976                     currentLoader = currentLoader.getParent();
 977                     iterator = iteratorFor(currentLoader);


1205      * this behavior is that a malformed provider-configuration file, like a
1206      * malformed class file, indicates a serious problem with the way the Java
1207      * virtual machine is configured or is being used.  As such it is
1208      * preferable to throw an error rather than try to recover or, even worse,
1209      * fail silently.</blockquote>
1210      *
1211      * <p> If this loader's provider caches are cleared by invoking the {@link
1212      * #reload() reload} method then existing iterators for this service
1213      * loader should be discarded.
1214      * The {@link java.util.Iterator#hasNext() hasNext} and {@link
1215      * java.util.Iterator#next() next} methods of the iterator throw {@link
1216      * java.util.ConcurrentModificationException ConcurrentModificationException}
1217      * if used after the provider cache has been cleared.
1218      *
1219      * <p> The iterator returned by this method does not support removal.
1220      * Invoking its {@link java.util.Iterator#remove() remove} method will
1221      * cause an {@link UnsupportedOperationException} to be thrown.
1222      *
1223      * @return  An iterator that lazily loads providers for this loader's
1224      *          service
1225      *
1226      * @revised 9
1227      * @spec JPMS
1228      */
1229     public Iterator<S> iterator() {
1230 
1231         // create lookup iterator if needed
1232         if (lookupIterator1 == null) {
1233             lookupIterator1 = newLookupIterator();
1234         }
1235 
1236         return new Iterator<S>() {
1237 
1238             // record reload count
1239             final int expectedReloadCount = ServiceLoader.this.reloadCount;
1240 
1241             // index into the cached providers list
1242             int index;
1243 
1244             /**
1245              * Throws ConcurrentModificationException if the list of cached
1246              * providers has been cleared by reload.
1247              */


1273             }
1274 
1275         };
1276     }
1277 
1278     /**
1279      * Returns a stream that lazily loads the available providers of this
1280      * loader's service. The stream elements are of type {@link Provider
1281      * Provider}, the {@code Provider}'s {@link Provider#get() get} method
1282      * must be invoked to get or instantiate the provider.
1283      *
1284      * <p> When processing the stream then providers that were previously
1285      * loaded by stream operations are processed first, in load order. It then
1286      * lazily loads any remaining providers. If a provider class cannot be
1287      * loaded, can't be assigned to the service type, or some other error is
1288      * thrown when locating the provider then it is wrapped with a {@code
1289      * ServiceConfigurationError} and thrown by whatever method caused the
1290      * provider to be loaded. </p>
1291      *
1292      * <p> If this loader's provider caches are cleared by invoking the {@link
1293      * #reload() reload} method then existing streams for this service loader
1294      * should be discarded. The returned stream's source {@code Spliterator} is
1295      * <em>fail-fast</em> and will throw {@link ConcurrentModificationException}
1296      * if the provider cache has been cleared. </p>
1297      *
1298      * <p> The following examples demonstrate usage. The first example
1299      * creates a stream of providers, the second example is the same except
1300      * that it sorts the providers by provider class name (and so locate all
1301      * providers).
1302      * <pre>{@code
1303      *    Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
1304      *            .stream()
1305      *            .map(Provider::get);
1306      *
1307      *    Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
1308      *            .stream()
1309      *            .sorted(Comparator.comparing(p -> p.type().getName()))
1310      *            .map(Provider::get);
1311      * }</pre>
1312      *
1313      * @return  A stream that lazily loads providers for this loader's service
1314      *
1315      * @since 9
1316      * @spec JPMS
1317      */
1318     public Stream<Provider<S>> stream() {
1319         // use cached providers as the source when all providers loaded
1320         if (loadedAllProviders) {
1321             return loadedProviders.stream();
1322         }
1323 
1324         // create lookup iterator if needed
1325         if (lookupIterator2 == null) {
1326             lookupIterator2 = newLookupIterator();
1327         }
1328 
1329         // use lookup iterator and cached providers as source
1330         Spliterator<Provider<S>> s = new ProviderSpliterator<>(lookupIterator2);
1331         return StreamSupport.stream(s, false);
1332     }
1333 
1334     private class ProviderSpliterator<T> implements Spliterator<Provider<T>> {
1335         final int expectedReloadCount = ServiceLoader.this.reloadCount;
1336         final Iterator<Provider<T>> iterator;


1411      * Creates a new service loader for the given service type and class
1412      * loader.
1413      *
1414      * @param  <S> the class of the service type
1415      *
1416      * @param  service
1417      *         The interface or abstract class representing the service
1418      *
1419      * @param  loader
1420      *         The class loader to be used to load provider-configuration files
1421      *         and provider classes, or {@code null} if the system class
1422      *         loader (or, failing that, the bootstrap class loader) is to be
1423      *         used
1424      *
1425      * @return A new service loader
1426      *
1427      * @throws ServiceConfigurationError
1428      *         if the service type is not accessible to the caller or the
1429      *         caller is in an explicit module and its module descriptor does
1430      *         not declare that it uses {@code service}
1431      *
1432      * @revised 9
1433      * @spec JPMS
1434      */
1435     @CallerSensitive
1436     public static <S> ServiceLoader<S> load(Class<S> service,
1437                                             ClassLoader loader)
1438     {
1439         return new ServiceLoader<>(Reflection.getCallerClass(), service, loader);
1440     }
1441 
1442     /**
1443      * Creates a new service loader for the given service type, using the
1444      * current thread's {@linkplain java.lang.Thread#getContextClassLoader
1445      * context class loader}.
1446      *
1447      * <p> An invocation of this convenience method of the form
1448      * <pre>{@code
1449      * ServiceLoader.load(service)
1450      * }</pre>
1451      *
1452      * is equivalent to
1453      *


1457      *
1458      * @apiNote Service loader objects obtained with this method should not be
1459      * cached VM-wide. For example, different applications in the same VM may
1460      * have different thread context class loaders. A lookup by one application
1461      * may locate a service provider that is only visible via its thread
1462      * context class loader and so is not suitable to be located by the other
1463      * application. Memory leaks can also arise. A thread local may be suited
1464      * to some applications.
1465      *
1466      * @param  <S> the class of the service type
1467      *
1468      * @param  service
1469      *         The interface or abstract class representing the service
1470      *
1471      * @return A new service loader
1472      *
1473      * @throws ServiceConfigurationError
1474      *         if the service type is not accessible to the caller or the
1475      *         caller is in an explicit module and its module descriptor does
1476      *         not declare that it uses {@code service}
1477      *
1478      * @revised 9
1479      * @spec JPMS
1480      */
1481     @CallerSensitive
1482     public static <S> ServiceLoader<S> load(Class<S> service) {
1483         ClassLoader cl = Thread.currentThread().getContextClassLoader();
1484         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1485     }
1486 
1487     /**
1488      * Creates a new service loader for the given service type, using the
1489      * {@linkplain ClassLoader#getPlatformClassLoader() platform class loader}.
1490      *
1491      * <p> This convenience method is equivalent to: </p>
1492      *
1493      * <pre>{@code
1494      * ServiceLoader.load(service, ClassLoader.getPlatformClassLoader())
1495      * }</pre>
1496      *
1497      * <p> This method is intended for use when only installed providers are
1498      * desired.  The resulting service will only find and load providers that
1499      * have been installed into the current Java virtual machine; providers on
1500      * the application's module path or class path will be ignored.
1501      *
1502      * @param  <S> the class of the service type
1503      *
1504      * @param  service
1505      *         The interface or abstract class representing the service
1506      *
1507      * @return A new service loader
1508      *
1509      * @throws ServiceConfigurationError
1510      *         if the service type is not accessible to the caller or the
1511      *         caller is in an explicit module and its module descriptor does
1512      *         not declare that it uses {@code service}
1513      *
1514      * @revised 9
1515      * @spec JPMS
1516      */
1517     @CallerSensitive
1518     public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
1519         ClassLoader cl = ClassLoader.getPlatformClassLoader();
1520         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1521     }
1522 
1523     /**
1524      * Creates a new service loader for the given service type that loads
1525      * service providers from modules in the given {@code Layer} and its
1526      * ancestors.
1527      *
1528      * @apiNote Unlike the other load methods defined here, the service type
1529      * is the second parameter. The reason for this is to avoid source
1530      * compatibility issues for code that uses {@code load(S, null)}.
1531      *
1532      * @param  <S> the class of the service type
1533      *
1534      * @param  layer
1535      *         The module Layer
1536      *
1537      * @param  service
1538      *         The interface or abstract class representing the service
1539      *
1540      * @return A new service loader
1541      *
1542      * @throws ServiceConfigurationError
1543      *         if the service type is not accessible to the caller or the
1544      *         caller is in an explicit module and its module descriptor does
1545      *         not declare that it uses {@code service}
1546      *
1547      * @since 9
1548      * @spec JPMS
1549      */
1550     @CallerSensitive
1551     public static <S> ServiceLoader<S> load(Layer layer, Class<S> service) {
1552         return new ServiceLoader<>(Reflection.getCallerClass(), layer, service);
1553     }
1554 
1555     /**
1556      * Load the first available provider of this loader's service. This
1557      * convenience method is equivalent to invoking the {@link #iterator()
1558      * iterator()} method and obtaining the first element. It therefore
1559      * returns the first element from the provider cache if possible, it
1560      * otherwise attempts to load and instantiate the first provider.
1561      *
1562      * <p> The following example loads the first available provider. If there
1563      * are no providers deployed then it uses a default implementation.
1564      * <pre>{@code
1565      *    CodecSet provider =
1566      *        ServiceLoader.load(CodecSet.class).findFirst().orElse(DEFAULT_CODECSET);
1567      * }</pre>
1568      * @return The first provider or empty {@code Optional} if no providers
1569      *         are located
1570      *
1571      * @throws ServiceConfigurationError
1572      *         If a provider class cannot be loaded, doesn't have the
1573      *         appropriate static factory method or constructor, can't be
1574      *         assigned to the service type, or if any other kind of exception
1575      *         or error is thrown when locating or instantiating the provider.
1576      *
1577      * @since 9
1578      * @spec JPMS
1579      */
1580     public Optional<S> findFirst() {
1581         Iterator<S> iterator = iterator();
1582         if (iterator.hasNext()) {
1583             return Optional.of(iterator.next());
1584         } else {
1585             return Optional.empty();
1586         }
1587     }
1588 
1589     /**
1590      * Clear this loader's provider cache so that all providers will be
1591      * reloaded.
1592      *
1593      * <p> After invoking this method, subsequent invocations of the {@link
1594      * #iterator() iterator} or {@link #stream() stream} methods will lazily
1595      * look up providers (and instantiate in the case of {@code iterator})
1596      * from scratch, just as is done by a newly-created loader.
1597      *
1598      * <p> This method is intended for use in situations in which new providers


< prev index next >