1 /*
   2  * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.io.BufferedReader;
  29 import java.io.IOException;
  30 import java.io.InputStream;
  31 import java.io.InputStreamReader;
  32 import java.lang.reflect.Constructor;
  33 import java.lang.reflect.InvocationTargetException;
  34 import java.lang.reflect.Layer;
  35 import java.lang.reflect.Method;
  36 import java.lang.reflect.Modifier;
  37 import java.lang.reflect.Module;
  38 import java.net.URL;
  39 import java.net.URLConnection;
  40 import java.security.AccessControlContext;
  41 import java.security.AccessController;
  42 import java.security.PrivilegedAction;
  43 import java.security.PrivilegedActionException;
  44 import java.security.PrivilegedExceptionAction;
  45 import java.util.function.Consumer;
  46 import java.util.function.Supplier;
  47 import java.util.stream.Stream;
  48 import java.util.stream.StreamSupport;
  49 
  50 import jdk.internal.loader.BootLoader;
  51 import jdk.internal.loader.ClassLoaders;
  52 import jdk.internal.misc.JavaLangAccess;
  53 import jdk.internal.misc.JavaLangReflectModuleAccess;
  54 import jdk.internal.misc.SharedSecrets;
  55 import jdk.internal.misc.VM;
  56 import jdk.internal.module.ServicesCatalog;
  57 import jdk.internal.module.ServicesCatalog.ServiceProvider;
  58 import jdk.internal.reflect.CallerSensitive;
  59 import jdk.internal.reflect.Reflection;
  60 
  61 
  62 /**
  63  * A simple service-provider loading facility.
  64  *
  65  * <p> A <i>service</i> is a well-known set of interfaces and (usually
  66  * abstract) classes.  A <i>service provider</i> is a specific implementation
  67  * of a service.  The classes in a provider typically implement the interfaces
  68  * and subclass the classes defined in the service itself.
  69  * Providers may be developed and deployed as modules and made available using
  70  * the application module path. Providers may alternatively be packaged as JAR
  71  * files and made available by adding them to the application class path. The
  72  * advantage of developing a provider as a module is that the provider can be
  73  * fully encapsulated to hide all details of its implementation.
  74  *
  75  * <p> For the purpose of loading, a service is represented by a single type,
  76  * that is, a single interface or abstract class.  (A concrete class can be
  77  * used, but this is not recommended.)  A provider of a given service contains
  78  * one or more concrete classes that extend this <i>service type</i> with data
  79  * and code specific to the provider.  The <i>provider class</i> is typically
  80  * not the entire provider itself but rather a proxy which contains enough
  81  * information to decide whether the provider is able to satisfy a particular
  82  * request together with code that can create the actual provider on demand.
  83  * The details of provider classes tend to be highly service-specific; no
  84  * single class or interface could possibly unify them, so no such type is
  85  * defined here.
  86  *
  87  * <p> Providers deployed as explicit modules on the module path are
  88  * instantiated by a <em>provider factory</em> or directly via the provider's
  89  * constructor. In the module declaration then the class name specified in the
  90  * <i>provides</i> clause is a provider factory if it is public and defines a
  91  * public static no-args method named "{@code provider}". The return type of
  92  * the method must be assignable to the <i>service</i> type. If the class is
  93  * not a provider factory then it is public with a public zero-argument
  94  * constructor. The requirement that the provider factory or provider class
  95  * be public helps to document the intent that the provider will be
  96  * instantiated by the service-provider loading facility.
  97  *
  98  * <p> As an example, suppose a module declares the following:
  99  *
 100  * <pre>{@code
 101  *     provides com.example.CodecSet with com.example.impl.StandardCodecs;
 102  *     provides com.example.CodecSet with com.example.impl.ExtendedCodecsFactory;
 103  * }</pre>
 104  *
 105  * <p> where {@code com.example.CodecSet} is the service type, {@code
 106  * com.example.impl.StandardCodecs} is a provider class that is public with a
 107  * public no-args constructor, {@code com.example.impl.ExtendedCodecsFactory}
 108  * is a public class that defines a public static no-args method named
 109  * "{@code provider}" with a return type that is {@code CodecSet} or a subtype
 110  * of. For this example then {@code StandardCodecs}'s no-arg constructor will
 111  * be used to instantiate {@code StandardCodecs}. {@code ExtendedCodecsFactory}
 112  * will be treated as a provider factory and {@code
 113  * ExtendedCodecsFactory.provider()} will be invoked to obtain the provider.
 114  *
 115  * <p> Providers deployed on the class path or as {@link
 116  * java.lang.module.ModuleDescriptor#isAutomatic automatic-modules} on the
 117  * module path must have a public zero-argument constructor.
 118  *
 119  * <p> An application or library using this loading facility and developed
 120  * and deployed as an explicit module must have an appropriate <i>uses</i>
 121  * clause in its <i>module descriptor</i> to declare that the module uses
 122  * implementations of the service. A corresponding requirement is that a
 123  * provider deployed as an explicit module must have an appropriate
 124  * <i>provides</i> clause in its module descriptor to declare that the module
 125  * provides an implementation of the service. The <i>uses</i> and
 126  * <i>provides</i> allow consumers of a service to be <i>linked</i> to modules
 127  * containing providers of the service.
 128  *
 129  * <p> A service provider that is packaged as a JAR file for the class path is
 130  * identified by placing a <i>provider-configuration file</i> in the resource
 131  * directory <tt>META-INF/services</tt>. The file's name is the fully-qualified
 132  * <a href="../lang/ClassLoader.html#name">binary name</a> of the service's
 133  * type. The file contains a list of fully-qualified binary names of concrete
 134  * provider classes, one per line.  Space and tab characters surrounding each
 135  * name, as well as blank lines, are ignored.  The comment character is
 136  * <tt>'#'</tt> (<tt>'\u0023'</tt>,
 137  * <font style="font-size:smaller;">NUMBER SIGN</font>); on
 138  * each line all characters following the first comment character are ignored.
 139  * The file must be encoded in UTF-8.
 140  * If a particular concrete provider class is named in more than one
 141  * configuration file, or is named in the same configuration file more than
 142  * once, then the duplicates are ignored.  The configuration file naming a
 143  * particular provider need not be in the same JAR file or other distribution
 144  * unit as the provider itself. The provider must be visible from the same
 145  * class loader that was initially queried to locate the configuration file;
 146  * note that this is not necessarily the class loader from which the file was
 147  * actually loaded.
 148  *
 149  * <p> Providers are located and instantiated lazily, that is, on demand.  A
 150  * service loader maintains a cache of the providers that have been loaded so
 151  * far. Each invocation of the {@link #iterator iterator} method returns an
 152  * iterator that first yields all of the elements cached from previous
 153  * iteration, in instantiation order, and then lazily locates and instantiates
 154  * any remaining providers, adding each one to the cache in turn.  Similarly,
 155  * each invocation of the {@link #stream stream} method returns a stream that
 156  * first processes all providers loaded by previous stream operations, in load
 157  * order, and then lazily locates any remaining providers. Caches are cleared
 158  * via the {@link #reload reload} method.
 159  *
 160  * <h2> Locating providers </h2>
 161  *
 162  * <p> The {@code load} methods locate providers using a class loader or module
 163  * {@link Layer layer}. When locating providers using a class loader then
 164  * providers in both named and unnamed modules may be located. When locating
 165  * providers using a module layer then only providers in named modules in
 166  * the layer (or parent layers) are located.
 167  *
 168  * <p> When locating providers using a class loader then any providers in named
 169  * modules defined to the class loader, or any class loader that is reachable
 170  * via parent delegation, are located. Additionally, providers in module layers
 171  * other than the {@link Layer#boot() boot} layer, where the module layer
 172  * contains modules defined to the class loader, or any class loader reachable
 173  * via parent delegation, are also located. For example, suppose there is a
 174  * module layer where each module is defined to its own class loader (see {@link
 175  * Layer#defineModulesWithManyLoaders defineModulesWithManyLoaders}). If the
 176  * {@code load} method is invoked to locate providers using any of these class
 177  * loaders for this layer then it will locate all of the providers in that
 178  * layer, irrespective of their defining class loader.
 179  *
 180  * <p> In the case of unnamed modules then the service configuration files are
 181  * located using the class loader's {@link ClassLoader#getResources(String)
 182  * ClassLoader.getResources(String)} method. Any providers listed should be
 183  * visible via the class loader specified to the {@code load} method. If a
 184  * provider in a named module is listed then it is ignored - this is to avoid
 185  * duplicates that would otherwise arise when a module has both a
 186  * <i>provides</i> clause and a service configuration file in {@code
 187  * META-INF/services} that lists the same provider.
 188  *
 189  * <h2> Ordering </h2>
 190  *
 191  * <p> Service loaders created to locate providers using a {@code ClassLoader}
 192  * locate providers as follows:
 193  * <ul>
 194  *     <li> Providers in named modules are located before providers on the
 195  *     class path (or more generally, unnamed modules). </li>
 196  *
 197  *     <li> When locating providers in named modules then the service loader
 198  *     will locate providers in modules defined to the class loader, then its
 199  *     parent class loader, its parent parent, and so on to the bootstrap class
 200  *     loader. If a {@code ClassLoader}, or any class loader in the parent
 201  *     delegation chain, defines modules in a custom module {@link Layer} then
 202  *     all providers in that layer are located, irrespective of their class
 203  *     loader. The ordering of modules defined to the same class loader, or the
 204  *     ordering of modules in a layer, is not defined. </li>
 205  *
 206  *     <li> If a named module declares more than one provider then the providers
 207  *     are located in the iteration order of the {@link
 208  *     java.lang.module.ModuleDescriptor.Provides#providers() providers} list.
 209  *     Providers added dynamically by instrumentation agents ({@link
 210  *     java.lang.instrument.Instrumentation#redefineModule redefineModule})
 211  *     are always located after providers declared by the module. </li>
 212  *
 213  *     <li> When locating providers in unnamed modules then the ordering is
 214  *     based on the order that the class loader's {@link
 215  *     ClassLoader#getResources(String) ClassLoader.getResources(String)}
 216  *     method finds the service configuration files. </li>
 217  * </ul>
 218  *
 219  * <p> Service loaders created to locate providers in a module {@link Layer}
 220  * will first locate providers in the layer, before locating providers in
 221  * parent layers. Traversal of parent layers is depth-first with each layer
 222  * visited at most once. For example, suppose L0 is the boot layer, L1 and
 223  * L2 are custom layers with L0 as their parent. Now suppose that L3 is
 224  * created with L1 and L2 as the parents (in that order). Using a service
 225  * loader to locate providers with L3 as the content will locate providers
 226  * in the following order: L3, L1, L0, L2. The ordering of modules in a layer
 227  * is not defined.
 228  *
 229  * <h2> Selection and filtering </h2>
 230  *
 231  * <p> Selecting a provider or filtering providers will usually involve invoking
 232  * a provider method. Where selection or filtering based on the provider class is
 233  * needed then it can be done using a {@link #stream() stream}. For example, the
 234  * following collects the providers that have a specific annotation:
 235  * <pre>{@code
 236  *     Set<CodecSet> providers = ServiceLoader.load(CodecSet.class)
 237  *            .stream()
 238  *            .filter(p -> p.type().isAnnotationPresent(Managed.class))
 239  *            .map(Provider::get)
 240  *            .collect(Collectors.toSet());
 241  * }</pre>
 242  *
 243  * <h2> Security </h2>
 244  *
 245  * <p> Service loaders always execute in the security context of the caller
 246  * of the iterator or stream methods and may also be restricted by the security
 247  * context of the caller that created the service loader.
 248  * Trusted system code should typically invoke the methods in this class, and
 249  * the methods of the iterators which they return, from within a privileged
 250  * security context.
 251  *
 252  * <h2> Concurrency </h2>
 253  *
 254  * <p> Instances of this class are not safe for use by multiple concurrent
 255  * threads.
 256  *
 257  * <h2> Null handling </h2>
 258  *
 259  * <p> Unless otherwise specified, passing a {@code null} argument to any
 260  * method in this class will cause a {@link NullPointerException} to be thrown.
 261  *
 262  * <h2> Example </h2>
 263  * <p> Suppose we have a service type <tt>com.example.CodecSet</tt> which is
 264  * intended to represent sets of encoder/decoder pairs for some protocol.  In
 265  * this case it is an abstract class with two abstract methods:
 266  *
 267  * <blockquote><pre>
 268  * public abstract Encoder getEncoder(String encodingName);
 269  * public abstract Decoder getDecoder(String encodingName);</pre></blockquote>
 270  *
 271  * Each method returns an appropriate object or <tt>null</tt> if the provider
 272  * does not support the given encoding.  Typical providers support more than
 273  * one encoding.
 274  *
 275  * <p> The <tt>CodecSet</tt> class creates and saves a single service instance
 276  * at initialization:
 277  *
 278  * <pre>{@code
 279  * private static ServiceLoader<CodecSet> codecSetLoader
 280  *     = ServiceLoader.load(CodecSet.class);
 281  * }</pre>
 282  *
 283  * <p> To locate an encoder for a given encoding name it defines a static
 284  * factory method which iterates through the known and available providers,
 285  * returning only when it has located a suitable encoder or has run out of
 286  * providers.
 287  *
 288  * <pre>{@code
 289  * public static Encoder getEncoder(String encodingName) {
 290  *     for (CodecSet cp : codecSetLoader) {
 291  *         Encoder enc = cp.getEncoder(encodingName);
 292  *         if (enc != null)
 293  *             return enc;
 294  *     }
 295  *     return null;
 296  * }}</pre>
 297  *
 298  * <p> A {@code getDecoder} method is defined similarly.
 299  *
 300  * <p> If the code creating and using the service loader is developed as
 301  * a module then its module descriptor will declare the usage with:
 302  * <pre>{@code uses com.example.CodecSet;}</pre>
 303  *
 304  * <p> Now suppose that {@code com.example.impl.StandardCodecs} is an
 305  * implementation of the {@code CodecSet} service and developed as a module.
 306  * In that case then the module with the service provider module will declare
 307  * this in its module descriptor:
 308  * <pre>{@code provides com.example.CodecSet with com.example.impl.StandardCodecs;
 309  * }</pre>
 310  *
 311  * <p> On the other hand, suppose {@code com.example.impl.StandardCodecs} is
 312  * packaged in a JAR file for the class path then the JAR file will contain a
 313  * file named:
 314  * <pre>{@code META-INF/services/com.example.CodecSet}</pre>
 315  * that contains the single line:
 316  * <pre>{@code com.example.impl.StandardCodecs    # Standard codecs}</pre>
 317  *
 318  * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If
 319  * the class path of a class loader that is used for provider loading includes
 320  * remote network URLs then those URLs will be dereferenced in the process of
 321  * searching for provider-configuration files.
 322  *
 323  * <p> This activity is normal, although it may cause puzzling entries to be
 324  * created in web-server logs.  If a web server is not configured correctly,
 325  * however, then this activity may cause the provider-loading algorithm to fail
 326  * spuriously.
 327  *
 328  * <p> A web server should return an HTTP 404 (Not Found) response when a
 329  * requested resource does not exist.  Sometimes, however, web servers are
 330  * erroneously configured to return an HTTP 200 (OK) response along with a
 331  * helpful HTML error page in such cases.  This will cause a {@link
 332  * ServiceConfigurationError} to be thrown when this class attempts to parse
 333  * the HTML page as a provider-configuration file.  The best solution to this
 334  * problem is to fix the misconfigured web server to return the correct
 335  * response code (HTTP 404) along with the HTML error page.
 336  *
 337  * @param  <S>
 338  *         The type of the service to be loaded by this loader
 339  *
 340  * @author Mark Reinhold
 341  * @since 1.6
 342  * @revised 9
 343  * @spec JPMS
 344  */
 345 
 346 public final class ServiceLoader<S>
 347     implements Iterable<S>
 348 {
 349     // The class or interface representing the service being loaded
 350     private final Class<S> service;
 351 
 352     // The class of the service type
 353     private final String serviceName;
 354 
 355     // The module Layer used to locate providers; null when locating
 356     // providers using a class loader
 357     private final Layer layer;
 358 
 359     // The class loader used to locate, load, and instantiate providers;
 360     // null when locating provider using a module Layer
 361     private final ClassLoader loader;
 362 
 363     // The access control context taken when the ServiceLoader is created
 364     private final AccessControlContext acc;
 365 
 366     // The lazy-lookup iterator for iterator operations
 367     private Iterator<Provider<S>> lookupIterator1;
 368     private final List<S> instantiatedProviders = new ArrayList<>();
 369 
 370     // The lazy-lookup iterator for stream operations
 371     private Iterator<Provider<S>> lookupIterator2;
 372     private final List<Provider<S>> loadedProviders = new ArrayList<>();
 373     private boolean loadedAllProviders; // true when all providers loaded
 374 
 375     // Incremented when reload is called
 376     private int reloadCount;
 377 
 378     private static JavaLangAccess LANG_ACCESS;
 379     private static JavaLangReflectModuleAccess JLRM_ACCESS;
 380     static {
 381         LANG_ACCESS = SharedSecrets.getJavaLangAccess();
 382         JLRM_ACCESS = SharedSecrets.getJavaLangReflectModuleAccess();
 383     }
 384 
 385     /**
 386      * Represents a service provider located by {@code ServiceLoader}.
 387      *
 388      * <p> When using a loader's {@link ServiceLoader#stream() stream()} method
 389      * then the elements are of type {@code Provider}. This allows processing
 390      * to select or filter on the provider class without instantiating the
 391      * provider. </p>
 392      *
 393      * @param  <S> The service type
 394      * @since 9
 395      * @spec JPMS
 396      */
 397     public static interface Provider<S> extends Supplier<S> {
 398         /**
 399          * Returns the provider type. There is no guarantee that this type is
 400          * accessible or that it has a public no-args constructor. The {@link
 401          * #get() get()} method should be used to obtain the provider instance.
 402          *
 403          * <p> When a module declares that the provider class is created by a
 404          * provider factory then this method returns the return type of its
 405          * public static "{@code provider()}" method.
 406          *
 407          * @return The provider type
 408          */
 409         Class<? extends S> type();
 410 
 411         /**
 412          * Returns an instance of the provider.
 413          *
 414          * @return An instance of the provider.
 415          *
 416          * @throws ServiceConfigurationError
 417          *         If the service provider cannot be instantiated, or in the
 418          *         case of a provider factory, the public static
 419          *         "{@code provider()}" method returns {@code null} or throws
 420          *         an error or exception. The {@code ServiceConfigurationError}
 421          *         will carry an appropriate cause where possible.
 422          */
 423         @Override S get();
 424     }
 425 
 426     /**
 427      * Initializes a new instance of this class for locating service providers
 428      * in a module Layer.
 429      *
 430      * @throws ServiceConfigurationError
 431      *         If {@code svc} is not accessible to {@code caller} or the caller
 432      *         module does not use the service type.
 433      */
 434     private ServiceLoader(Class<?> caller, Layer layer, Class<S> svc) {
 435         Objects.requireNonNull(caller);
 436         Objects.requireNonNull(layer);
 437         Objects.requireNonNull(svc);
 438         checkCaller(caller, svc);
 439 
 440         this.service = svc;
 441         this.serviceName = svc.getName();
 442         this.layer = layer;
 443         this.loader = null;
 444         this.acc = (System.getSecurityManager() != null)
 445                 ? AccessController.getContext()
 446                 : null;
 447     }
 448 
 449     /**
 450      * Initializes a new instance of this class for locating service providers
 451      * via a class loader.
 452      *
 453      * @throws ServiceConfigurationError
 454      *         If {@code svc} is not accessible to {@code caller} or the caller
 455      *         module does not use the service type.
 456      */
 457     private ServiceLoader(Class<?> caller, Class<S> svc, ClassLoader cl) {
 458         Objects.requireNonNull(svc);
 459 
 460         if (VM.isBooted()) {
 461             checkCaller(caller, svc);
 462             if (cl == null) {
 463                 cl = ClassLoader.getSystemClassLoader();
 464             }
 465         } else {
 466 
 467             // if we get here then it means that ServiceLoader is being used
 468             // before the VM initialization has completed. At this point then
 469             // only code in the java.base should be executing.
 470             Module callerModule = caller.getModule();
 471             Module base = Object.class.getModule();
 472             Module svcModule = svc.getModule();
 473             if (callerModule != base || svcModule != base) {
 474                 fail(svc, "not accessible to " + callerModule + " during VM init");
 475             }
 476 
 477             // restricted to boot loader during startup
 478             cl = null;
 479         }
 480 
 481         this.service = svc;
 482         this.serviceName = svc.getName();
 483         this.layer = null;
 484         this.loader = cl;
 485         this.acc = (System.getSecurityManager() != null)
 486                 ? AccessController.getContext()
 487                 : null;
 488     }
 489 
 490     /**
 491      * Initializes a new instance of this class for locating service providers
 492      * via a class loader.
 493      *
 494      * @apiNote For use by ResourceBundle
 495      *
 496      * @throws ServiceConfigurationError
 497      *         If the caller module does not use the service type.
 498      */
 499     private ServiceLoader(Module callerModule, Class<S> svc, ClassLoader cl) {
 500         if (!callerModule.canUse(svc)) {
 501             fail(svc, callerModule + " does not declare `uses`");
 502         }
 503 
 504         this.service = Objects.requireNonNull(svc);
 505         this.serviceName = svc.getName();
 506         this.layer = null;
 507         this.loader = cl;
 508         this.acc = (System.getSecurityManager() != null)
 509                 ? AccessController.getContext()
 510                 : null;
 511     }
 512 
 513     /**
 514      * Checks that the given service type is accessible to types in the given
 515      * module, and check that the module declare that it uses the service type. ??
 516      */
 517     private static void checkCaller(Class<?> caller, Class<?> svc) {
 518         Module callerModule = caller.getModule();
 519 
 520         // Check access to the service type
 521         int mods = svc.getModifiers();
 522         if (!Reflection.verifyMemberAccess(caller, svc, null, mods)) {
 523             fail(svc, "service type not accessible to " + callerModule);
 524         }
 525 
 526         // If the caller is in a named module then it should "uses" the
 527         // service type
 528         if (!callerModule.canUse(svc)) {
 529             fail(svc, callerModule + " does not declare `uses`");
 530         }
 531     }
 532 
 533     private static void fail(Class<?> service, String msg, Throwable cause)
 534         throws ServiceConfigurationError
 535     {
 536         throw new ServiceConfigurationError(service.getName() + ": " + msg,
 537                                             cause);
 538     }
 539 
 540     private static void fail(Class<?> service, String msg)
 541         throws ServiceConfigurationError
 542     {
 543         throw new ServiceConfigurationError(service.getName() + ": " + msg);
 544     }
 545 
 546     private static void fail(Class<?> service, URL u, int line, String msg)
 547         throws ServiceConfigurationError
 548     {
 549         fail(service, u + ":" + line + ": " + msg);
 550     }
 551 
 552     /**
 553      * Uses Class.forName to load a provider class in a module.
 554      *
 555      * @throws ServiceConfigurationError
 556      *         If the class cannot be loaded
 557      */
 558     private Class<?> loadProviderInModule(Module module, String cn) {
 559         Class<?> clazz = null;
 560         if (acc == null) {
 561             try {
 562                 clazz = Class.forName(module, cn);
 563             } catch (LinkageError e) {
 564                 fail(service, "Unable to load " + cn, e);
 565             }
 566         } else {
 567             PrivilegedExceptionAction<Class<?>> pa = () -> Class.forName(module, cn);
 568             try {
 569                 clazz = AccessController.doPrivileged(pa);
 570             } catch (PrivilegedActionException pae) {
 571                 Throwable x = pae.getCause();
 572                 fail(service, "Unable to load " + cn, x);
 573                 return null;
 574             }
 575         }
 576         if (clazz == null)
 577             fail(service, "Provider " + cn  + " not found");
 578         return clazz;
 579     }
 580 
 581     /**
 582      * A Provider implementation that supports invoking, with reduced
 583      * permissions, the static factory to obtain the provider or the
 584      * provider's no-arg constructor.
 585      */
 586     private final static class ProviderImpl<S> implements Provider<S> {
 587         final Class<S> service;
 588         final AccessControlContext acc;
 589 
 590         final Method factoryMethod;  // factory method or null
 591         final Class<? extends S> type;
 592         final Constructor<? extends S> ctor; // public no-args constructor or null
 593 
 594         /**
 595          * Creates a Provider.
 596          *
 597          * @param service
 598          *        The service type
 599          * @param clazz
 600          *        The provider (or provider factory) class
 601          * @param acc
 602          *        The access control context when running with security manager
 603          *
 604          * @throws ServiceConfigurationError
 605          *         If the class is not public; If the class defines a public
 606          *         static provider() method with a return type that is assignable
 607          *         to the service type or the class is not a provider class with
 608          *         a public no-args constructor.
 609          */
 610         @SuppressWarnings("unchecked")
 611         ProviderImpl(Class<?> service, Class<?> clazz, AccessControlContext acc) {
 612             this.service = (Class<S>) service;
 613             this.acc = acc;
 614 
 615             int mods = clazz.getModifiers();
 616             if (!Modifier.isPublic(mods)) {
 617                 fail(service, clazz + " is not public");
 618             }
 619 
 620             // if the class is in an explicit module then see if it is
 621             // a provider factory class
 622             Method factoryMethod = null;
 623             if (inExplicitModule(clazz)) {
 624                 factoryMethod = findStaticProviderMethod(clazz);
 625                 if (factoryMethod != null) {
 626                     Class<?> returnType = factoryMethod.getReturnType();
 627                     if (!service.isAssignableFrom(returnType)) {
 628                         fail(service, factoryMethod + " return type not a subtype");
 629                     }
 630                 }
 631             }
 632             this.factoryMethod = factoryMethod;
 633 
 634             if (factoryMethod == null) {
 635                 // no factory method so must have a public no-args constructor
 636                 if (!service.isAssignableFrom(clazz)) {
 637                     fail(service, clazz.getName() + " not a subtype");
 638                 }
 639                 this.type = (Class<? extends S>) clazz;
 640                 this.ctor = (Constructor<? extends S>) getConstructor(clazz);
 641             } else {
 642                 this.type = (Class<? extends S>) factoryMethod.getReturnType();
 643                 this.ctor = null;
 644             }
 645         }
 646 
 647         @Override
 648         public Class<? extends S> type() {
 649             return type;
 650         }
 651 
 652         @Override
 653         public S get() {
 654             if (factoryMethod != null) {
 655                 return invokeFactoryMethod();
 656             } else {
 657                 return newInstance();
 658             }
 659         }
 660 
 661         /**
 662          * Returns {@code true} if the provider is in an explicit module
 663          */
 664         private boolean inExplicitModule(Class<?> clazz) {
 665             Module module = clazz.getModule();
 666             return module.isNamed() && !module.getDescriptor().isAutomatic();
 667         }
 668 
 669         /**
 670          * Returns the public static provider method if found.
 671          *
 672          * @throws ServiceConfigurationError if there is an error finding the
 673          *         provider method
 674          */
 675         private Method findStaticProviderMethod(Class<?> clazz) {
 676             Method method = null;
 677             try {
 678                 method = LANG_ACCESS.getMethodOrNull(clazz, "provider");
 679             } catch (Throwable x) {
 680                 fail(service, "Unable to get public provider() method", x);
 681             }
 682             if (method != null) {
 683                 int mods = method.getModifiers();
 684                 if (Modifier.isStatic(mods)) {
 685                     assert Modifier.isPublic(mods);
 686                     Method m = method;
 687                     PrivilegedAction<Void> pa = () -> {
 688                         m.setAccessible(true);
 689                         return null;
 690                     };
 691                     AccessController.doPrivileged(pa);
 692                     return method;
 693                 }
 694             }
 695             return null;
 696         }
 697 
 698         /**
 699          * Returns the public no-arg constructor of a class.
 700          *
 701          * @throws ServiceConfigurationError if the class does not have
 702          *         public no-arg constructor
 703          */
 704         private Constructor<?> getConstructor(Class<?> clazz) {
 705             PrivilegedExceptionAction<Constructor<?>> pa
 706                 = new PrivilegedExceptionAction<>() {
 707                     @Override
 708                     public Constructor<?> run() throws Exception {
 709                         Constructor<?> ctor = clazz.getConstructor();
 710                         if (inExplicitModule(clazz))
 711                             ctor.setAccessible(true);
 712                         return ctor;
 713                     }
 714                 };
 715             Constructor<?> ctor = null;
 716             try {
 717                 ctor = AccessController.doPrivileged(pa);
 718             } catch (Throwable x) {
 719                 if (x instanceof PrivilegedActionException)
 720                     x = x.getCause();
 721                 String cn = clazz.getName();
 722                 fail(service, cn + " Unable to get public no-arg constructor", x);
 723             }
 724             return ctor;
 725         }
 726 
 727         /**
 728          * Invokes the provider's "provider" method to instantiate a provider.
 729          * When running with a security manager then the method runs with
 730          * permissions that are restricted by the security context of whatever
 731          * created this loader.
 732          */
 733         private S invokeFactoryMethod() {
 734             Object result = null;
 735             Throwable exc = null;
 736             if (acc == null) {
 737                 try {
 738                     result = factoryMethod.invoke(null);
 739                 } catch (Throwable x) {
 740                     exc = x;
 741                 }
 742             } else {
 743                 PrivilegedExceptionAction<?> pa = new PrivilegedExceptionAction<>() {
 744                     @Override
 745                     public Object run() throws Exception {
 746                         return factoryMethod.invoke(null);
 747                     }
 748                 };
 749                 // invoke factory method with permissions restricted by acc
 750                 try {
 751                     result = AccessController.doPrivileged(pa, acc);
 752                 } catch (PrivilegedActionException pae) {
 753                     exc = pae.getCause();
 754                 }
 755             }
 756             if (exc != null) {
 757                 if (exc instanceof InvocationTargetException)
 758                     exc = exc.getCause();
 759                 fail(service, factoryMethod + " failed", exc);
 760             }
 761             if (result == null) {
 762                 fail(service, factoryMethod + " returned null");
 763             }
 764             @SuppressWarnings("unchecked")
 765             S p = (S) result;
 766             return p;
 767         }
 768 
 769         /**
 770          * Invokes Constructor::newInstance to instantiate a provider. When running
 771          * with a security manager then the constructor runs with permissions that
 772          * are restricted by the security context of whatever created this loader.
 773          */
 774         private S newInstance() {
 775             S p = null;
 776             Throwable exc = null;
 777             if (acc == null) {
 778                 try {
 779                     p = ctor.newInstance();
 780                 } catch (Throwable x) {
 781                     exc = x;
 782                 }
 783             } else {
 784                 PrivilegedExceptionAction<S> pa = new PrivilegedExceptionAction<>() {
 785                     @Override
 786                     public S run() throws Exception {
 787                         return ctor.newInstance();
 788                     }
 789                 };
 790                 // invoke constructor with permissions restricted by acc
 791                 try {
 792                     p = AccessController.doPrivileged(pa, acc);
 793                 } catch (PrivilegedActionException pae) {
 794                     exc = pae.getCause();
 795                 }
 796             }
 797             if (exc != null) {
 798                 if (exc instanceof InvocationTargetException)
 799                     exc = exc.getCause();
 800                 String cn = ctor.getDeclaringClass().getName();
 801                 fail(service,
 802                      "Provider " + cn + " could not be instantiated", exc);
 803             }
 804             return p;
 805         }
 806 
 807         // For now, equals/hashCode uses the access control context to ensure
 808         // that two Providers created with different contexts are not equal
 809         // when running with a security manager.
 810 
 811         @Override
 812         public int hashCode() {
 813             return Objects.hash(type, acc);
 814         }
 815 
 816         @Override
 817         public boolean equals(Object ob) {
 818             if (!(ob instanceof ProviderImpl))
 819                 return false;
 820             @SuppressWarnings("unchecked")
 821             ProviderImpl<?> that = (ProviderImpl<?>)ob;
 822             return this.type == that.type
 823                     && Objects.equals(this.acc, that.acc);
 824         }
 825     }
 826 
 827     /**
 828      * Implements lazy service provider lookup of service providers that
 829      * are provided by modules in a module Layer (or parent layers)
 830      */
 831     private final class LayerLookupIterator<T>
 832         implements Iterator<Provider<T>>
 833     {
 834         Deque<Layer> stack = new ArrayDeque<>();
 835         Set<Layer> visited = new HashSet<>();
 836         Iterator<ServiceProvider> iterator;
 837         ServiceProvider next;  // next provider to load
 838 
 839         LayerLookupIterator() {
 840             visited.add(layer);
 841             stack.push(layer);
 842         }
 843 
 844         private Iterator<ServiceProvider> providers(Layer layer) {
 845             ServicesCatalog catalog = JLRM_ACCESS.getServicesCatalog(layer);
 846             return catalog.findServices(serviceName).iterator();
 847         }
 848 
 849         @Override
 850         public boolean hasNext() {
 851             // already have the next provider cached
 852             if (next != null)
 853                 return true;
 854 
 855             while (true) {
 856 
 857                 // next provider (or provider factory)
 858                 if (iterator != null && iterator.hasNext()) {
 859                     next = iterator.next();
 860                     return true;
 861                 }
 862 
 863                 // next layer (DFS order)
 864                 if (stack.isEmpty())
 865                     return false;
 866 
 867                 Layer layer = stack.pop();
 868                 List<Layer> parents = layer.parents();
 869                 for (int i = parents.size() - 1; i >= 0; i--) {
 870                     Layer parent = parents.get(i);
 871                     if (!visited.contains(parent)) {
 872                         visited.add(parent);
 873                         stack.push(parent);
 874                     }
 875                 }
 876                 iterator = providers(layer);
 877             }
 878         }
 879 
 880         @Override
 881         public Provider<T> next() {
 882             if (!hasNext())
 883                 throw new NoSuchElementException();
 884 
 885             // take next provider
 886             ServiceProvider provider = next;
 887             next = null;
 888 
 889             // attempt to load provider
 890             Module module = provider.module();
 891             String cn = provider.providerName();
 892             Class<?> clazz = loadProviderInModule(module, cn);
 893             return new ProviderImpl<T>(service, clazz, acc);
 894         }
 895     }
 896 
 897     /**
 898      * Implements lazy service provider lookup of service providers that
 899      * are provided by modules defined to a class loader or to modules in
 900      * layers with a module defined to the class loader.
 901      */
 902     private final class ModuleServicesLookupIterator<T>
 903         implements Iterator<Provider<T>>
 904     {
 905         ClassLoader currentLoader;
 906         Iterator<ServiceProvider> iterator;
 907         ServiceProvider next;  // next provider to load
 908 
 909         ModuleServicesLookupIterator() {
 910             this.currentLoader = loader;
 911             this.iterator = iteratorFor(loader);
 912         }
 913 
 914         /**
 915          * Returns iterator to iterate over the implementations of {@code
 916          * service} in the given layer.
 917          */
 918         private List<ServiceProvider> providers(Layer layer) {
 919             ServicesCatalog catalog = JLRM_ACCESS.getServicesCatalog(layer);
 920             return catalog.findServices(serviceName);
 921         }
 922 
 923         /**
 924          * Returns an iterator to iterate over the implementations of {@code
 925          * service} in modules defined to the given class loader or in custom
 926          * layers with a module defined to this class loader.
 927          */
 928         private Iterator<ServiceProvider> iteratorFor(ClassLoader loader) {
 929 
 930             // modules defined to this class loader
 931             ServicesCatalog catalog;
 932             if (loader == null) {
 933                 catalog = BootLoader.getServicesCatalog();
 934             } else {
 935                 catalog = ServicesCatalog.getServicesCatalogOrNull(loader);
 936             }
 937             List<ServiceProvider> providers;
 938             if (catalog == null) {
 939                 providers = List.of();
 940             } else {
 941                 providers = catalog.findServices(serviceName);
 942             }
 943 
 944             // modules in custom layers that define modules to the class loader
 945             if (loader == null) {
 946                 return providers.iterator();
 947             } else {
 948                 List<ServiceProvider> allProviders = new ArrayList<>(providers);
 949                 Layer bootLayer = Layer.boot();
 950                 Iterator<Layer> iterator = JLRM_ACCESS.layers(loader).iterator();
 951                 while (iterator.hasNext()) {
 952                     Layer layer = iterator.next();
 953                     if (layer != bootLayer) {
 954                         allProviders.addAll(providers(layer));
 955                     }
 956                 }
 957                 return allProviders.iterator();
 958             }
 959         }
 960 
 961         @Override
 962         public boolean hasNext() {
 963             // already have the next provider cached
 964             if (next != null)
 965                 return true;
 966 
 967             while (true) {
 968                 if (iterator.hasNext()) {
 969                     next = iterator.next();
 970                     return true;
 971                 }
 972 
 973                 // move to the next class loader if possible
 974                 if (currentLoader == null) {
 975                     return false;
 976                 } else {
 977                     currentLoader = currentLoader.getParent();
 978                     iterator = iteratorFor(currentLoader);
 979                 }
 980             }
 981         }
 982 
 983         @Override
 984         public Provider<T> next() {
 985             if (!hasNext())
 986                 throw new NoSuchElementException();
 987 
 988             // take next provider
 989             ServiceProvider provider = next;
 990             next = null;
 991 
 992             // attempt to load provider
 993             Module module = provider.module();
 994             String cn = provider.providerName();
 995             Class<?> clazz = loadProviderInModule(module, cn);
 996             return new ProviderImpl<T>(service, clazz, acc);
 997         }
 998     }
 999 
1000     /**
1001      * Implements lazy service provider lookup where the service providers are
1002      * configured via service configuration files. Service providers in named
1003      * modules are silently ignored by this lookup iterator.
1004      */
1005     private final class LazyClassPathLookupIterator<T>
1006         implements Iterator<Provider<T>>
1007     {
1008         static final String PREFIX = "META-INF/services/";
1009 
1010         Enumeration<URL> configs;
1011         Iterator<String> pending;
1012         Class<?> nextClass;
1013         String nextErrorMessage;  // when hasNext fails with CNFE
1014 
1015         LazyClassPathLookupIterator() { }
1016 
1017         /**
1018          * Parse a single line from the given configuration file, adding the
1019          * name on the line to the names list.
1020          */
1021         private int parseLine(URL u, BufferedReader r, int lc, Set<String> names)
1022             throws IOException
1023         {
1024             String ln = r.readLine();
1025             if (ln == null) {
1026                 return -1;
1027             }
1028             int ci = ln.indexOf('#');
1029             if (ci >= 0) ln = ln.substring(0, ci);
1030             ln = ln.trim();
1031             int n = ln.length();
1032             if (n != 0) {
1033                 if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
1034                     fail(service, u, lc, "Illegal configuration-file syntax");
1035                 int cp = ln.codePointAt(0);
1036                 if (!Character.isJavaIdentifierStart(cp))
1037                     fail(service, u, lc, "Illegal provider-class name: " + ln);
1038                 int start = Character.charCount(cp);
1039                 for (int i = start; i < n; i += Character.charCount(cp)) {
1040                     cp = ln.codePointAt(i);
1041                     if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
1042                         fail(service, u, lc, "Illegal provider-class name: " + ln);
1043                 }
1044                 names.add(ln);
1045             }
1046             return lc + 1;
1047         }
1048 
1049         /**
1050          * Parse the content of the given URL as a provider-configuration file.
1051          */
1052         private Iterator<String> parse(URL u) {
1053             Set<String> names = new LinkedHashSet<>(); // preserve insertion order
1054             try {
1055                 URLConnection uc = u.openConnection();
1056                 uc.setUseCaches(false);
1057                 try (InputStream in = uc.getInputStream();
1058                      BufferedReader r
1059                          = new BufferedReader(new InputStreamReader(in, "utf-8")))
1060                 {
1061                     int lc = 1;
1062                     while ((lc = parseLine(u, r, lc, names)) >= 0);
1063                 }
1064             } catch (IOException x) {
1065                 fail(service, "Error accessing configuration file", x);
1066             }
1067             return names.iterator();
1068         }
1069 
1070         private boolean hasNextService() {
1071             if (nextClass != null || nextErrorMessage != null) {
1072                 return true;
1073             }
1074 
1075             Class<?> clazz = null;
1076             do {
1077                 if (configs == null) {
1078                     try {
1079                         String fullName = PREFIX + service.getName();
1080                         if (loader == null) {
1081                             configs = ClassLoader.getSystemResources(fullName);
1082                         } else if (loader == ClassLoaders.platformClassLoader()) {
1083                             // The platform classloader doesn't have a class path,
1084                             // but the boot loader might.
1085                             if (BootLoader.hasClassPath()) {
1086                                 configs = BootLoader.findResources(fullName);
1087                             } else {
1088                                 configs = Collections.emptyEnumeration();
1089                             }
1090                         } else {
1091                             configs = loader.getResources(fullName);
1092                         }
1093                     } catch (IOException x) {
1094                         fail(service, "Error locating configuration files", x);
1095                     }
1096                 }
1097                 while ((pending == null) || !pending.hasNext()) {
1098                     if (!configs.hasMoreElements()) {
1099                         return false;
1100                     }
1101                     pending = parse(configs.nextElement());
1102                 }
1103                 String cn = pending.next();
1104                 try {
1105                     clazz = Class.forName(cn, false, loader);
1106                 } catch (ClassNotFoundException x) {
1107                     // don't throw SCE here to long standing behavior
1108                     nextErrorMessage = "Provider " + cn + " not found";
1109                     return true;
1110                 }
1111 
1112             } while (clazz.getModule().isNamed()); // ignore if in named module
1113 
1114             nextClass = clazz;
1115             return true;
1116         }
1117 
1118         private Provider<T> nextService() {
1119             if (!hasNextService())
1120                 throw new NoSuchElementException();
1121 
1122             // throw any SCE with error recorded by hasNext
1123             if (nextErrorMessage != null) {
1124                 String msg = nextErrorMessage;
1125                 nextErrorMessage = null;
1126                 fail(service, msg);
1127             }
1128 
1129             // return next provider
1130             Class<?> clazz = nextClass;
1131             nextClass = null;
1132             return new ProviderImpl<T>(service, clazz, acc);
1133         }
1134 
1135         @Override
1136         public boolean hasNext() {
1137             if (acc == null) {
1138                 return hasNextService();
1139             } else {
1140                 PrivilegedAction<Boolean> action = new PrivilegedAction<>() {
1141                     public Boolean run() { return hasNextService(); }
1142                 };
1143                 return AccessController.doPrivileged(action, acc);
1144             }
1145         }
1146 
1147         @Override
1148         public Provider<T> next() {
1149             if (acc == null) {
1150                 return nextService();
1151             } else {
1152                 PrivilegedAction<Provider<T>> action = new PrivilegedAction<>() {
1153                     public Provider<T> run() { return nextService(); }
1154                 };
1155                 return AccessController.doPrivileged(action, acc);
1156             }
1157         }
1158     }
1159 
1160     /**
1161      * Returns a new lookup iterator.
1162      */
1163     private Iterator<Provider<S>> newLookupIterator() {
1164         assert layer == null || loader == null;
1165         if (layer != null) {
1166             return new LayerLookupIterator<>();
1167         } else {
1168             Iterator<Provider<S>> first = new ModuleServicesLookupIterator<>();
1169             Iterator<Provider<S>> second = new LazyClassPathLookupIterator<>();
1170             return new Iterator<Provider<S>>() {
1171                 @Override
1172                 public boolean hasNext() {
1173                     return (first.hasNext() || second.hasNext());
1174                 }
1175                 @Override
1176                 public Provider<S> next() {
1177                     if (first.hasNext()) {
1178                         return first.next();
1179                     } else if (second.hasNext()) {
1180                         return second.next();
1181                     } else {
1182                         throw new NoSuchElementException();
1183                     }
1184                 }
1185             };
1186         }
1187     }
1188 
1189     /**
1190      * Lazily load and instantiate the available providers of this loader's
1191      * service.
1192      *
1193      * <p> The iterator returned by this method first yields all of the
1194      * elements of the provider cache, in the order that they were loaded.
1195      * It then lazily loads and instantiates any remaining providers,
1196      * adding each one to the cache in turn.
1197      *
1198      * <p> To achieve laziness the actual work of locating and instantiating
1199      * providers must be done by the iterator itself. Its {@link
1200      * java.util.Iterator#hasNext hasNext} and {@link java.util.Iterator#next
1201      * next} methods can therefore throw a {@link ServiceConfigurationError}
1202      * if a provider class cannot be loaded, doesn't have an appropriate static
1203      * factory method or constructor, can't be assigned to the service type or
1204      * if any other kind of exception or error is thrown as the next provider
1205      * is located and instantiated. To write robust code it is only necessary
1206      * to catch {@link ServiceConfigurationError} when using a service iterator.
1207      *
1208      * <p> If such an error is thrown then subsequent invocations of the
1209      * iterator will make a best effort to locate and instantiate the next
1210      * available provider, but in general such recovery cannot be guaranteed.
1211      *
1212      * <blockquote style="font-size: smaller; line-height: 1.2"><span
1213      * style="padding-right: 1em; font-weight: bold">Design Note</span>
1214      * Throwing an error in these cases may seem extreme.  The rationale for
1215      * this behavior is that a malformed provider-configuration file, like a
1216      * malformed class file, indicates a serious problem with the way the Java
1217      * virtual machine is configured or is being used.  As such it is
1218      * preferable to throw an error rather than try to recover or, even worse,
1219      * fail silently.</blockquote>
1220      *
1221      * <p> If this loader's provider caches are cleared by invoking the {@link
1222      * #reload() reload} method then existing iterators for this service
1223      * loader should be discarded.
1224      * The {@link java.util.Iterator#hasNext() hasNext} and {@link
1225      * java.util.Iterator#next() next} methods of the iterator throw {@link
1226      * java.util.ConcurrentModificationException ConcurrentModificationException}
1227      * if used after the provider cache has been cleared.
1228      *
1229      * <p> The iterator returned by this method does not support removal.
1230      * Invoking its {@link java.util.Iterator#remove() remove} method will
1231      * cause an {@link UnsupportedOperationException} to be thrown.
1232      *
1233      * @return  An iterator that lazily loads providers for this loader's
1234      *          service
1235      *
1236      * @revised 9
1237      * @spec JPMS
1238      */
1239     public Iterator<S> iterator() {
1240 
1241         // create lookup iterator if needed
1242         if (lookupIterator1 == null) {
1243             lookupIterator1 = newLookupIterator();
1244         }
1245 
1246         return new Iterator<S>() {
1247 
1248             // record reload count
1249             final int expectedReloadCount = ServiceLoader.this.reloadCount;
1250 
1251             // index into the cached providers list
1252             int index;
1253 
1254             /**
1255              * Throws ConcurrentModificationException if the list of cached
1256              * providers has been cleared by reload.
1257              */
1258             private void checkReloadCount() {
1259                 if (ServiceLoader.this.reloadCount != expectedReloadCount)
1260                     throw new ConcurrentModificationException();
1261             }
1262 
1263             @Override
1264             public boolean hasNext() {
1265                 checkReloadCount();
1266                 if (index < instantiatedProviders.size())
1267                     return true;
1268                 return lookupIterator1.hasNext();
1269             }
1270 
1271             @Override
1272             public S next() {
1273                 checkReloadCount();
1274                 S next;
1275                 if (index < instantiatedProviders.size()) {
1276                     next = instantiatedProviders.get(index);
1277                 } else {
1278                     next = lookupIterator1.next().get();
1279                     instantiatedProviders.add(next);
1280                 }
1281                 index++;
1282                 return next;
1283             }
1284 
1285         };
1286     }
1287 
1288     /**
1289      * Returns a stream that lazily loads the available providers of this
1290      * loader's service. The stream elements are of type {@link Provider
1291      * Provider}, the {@code Provider}'s {@link Provider#get() get} method
1292      * must be invoked to get or instantiate the provider.
1293      *
1294      * <p> When processing the stream then providers that were previously
1295      * loaded by stream operations are processed first, in load order. It then
1296      * lazily loads any remaining providers. If a provider class cannot be
1297      * loaded, can't be assigned to the service type, or some other error is
1298      * thrown when locating the provider then it is wrapped with a {@code
1299      * ServiceConfigurationError} and thrown by whatever method caused the
1300      * provider to be loaded. </p>
1301      *
1302      * <p> If this loader's provider caches are cleared by invoking the {@link
1303      * #reload() reload} method then existing streams for this service loader
1304      * should be discarded. The returned stream's source {@code Spliterator} is
1305      * <em>fail-fast</em> and will throw {@link ConcurrentModificationException}
1306      * if the provider cache has been cleared. </p>
1307      *
1308      * <p> The following examples demonstrate usage. The first example
1309      * creates a stream of providers, the second example is the same except
1310      * that it sorts the providers by provider class name (and so locate all
1311      * providers).
1312      * <pre>{@code
1313      *    Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
1314      *            .stream()
1315      *            .map(Provider::get);
1316      *
1317      *    Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class)
1318      *            .stream()
1319      *            .sorted(Comparator.comparing(p -> p.type().getName()))
1320      *            .map(Provider::get);
1321      * }</pre>
1322      *
1323      * @return  A stream that lazily loads providers for this loader's service
1324      *
1325      * @since 9
1326      * @spec JPMS
1327      */
1328     public Stream<Provider<S>> stream() {
1329         // use cached providers as the source when all providers loaded
1330         if (loadedAllProviders) {
1331             return loadedProviders.stream();
1332         }
1333 
1334         // create lookup iterator if needed
1335         if (lookupIterator2 == null) {
1336             lookupIterator2 = newLookupIterator();
1337         }
1338 
1339         // use lookup iterator and cached providers as source
1340         Spliterator<Provider<S>> s = new ProviderSpliterator<>(lookupIterator2);
1341         return StreamSupport.stream(s, false);
1342     }
1343 
1344     private class ProviderSpliterator<T> implements Spliterator<Provider<T>> {
1345         final int expectedReloadCount = ServiceLoader.this.reloadCount;
1346         final Iterator<Provider<T>> iterator;
1347         int index;
1348 
1349         ProviderSpliterator(Iterator<Provider<T>> iterator) {
1350             this.iterator = iterator;
1351         }
1352 
1353         @Override
1354         public Spliterator<Provider<T>> trySplit() {
1355             return null;
1356         }
1357 
1358         @Override
1359         @SuppressWarnings("unchecked")
1360         public boolean tryAdvance(Consumer<? super Provider<T>> action) {
1361             if (ServiceLoader.this.reloadCount != expectedReloadCount)
1362                 throw new ConcurrentModificationException();
1363             Provider<T> next = null;
1364             if (index < loadedProviders.size()) {
1365                 next = (Provider<T>) loadedProviders.get(index++);
1366             } else if (iterator.hasNext()) {
1367                 next = iterator.next();
1368             } else {
1369                 loadedAllProviders = true;
1370             }
1371             if (next != null) {
1372                 action.accept(next);
1373                 return true;
1374             } else {
1375                 return false;
1376             }
1377         }
1378 
1379         @Override
1380         public int characteristics() {
1381             // not IMMUTABLE as structural interference possible
1382             // not NOTNULL so that the characteristics are a subset of the
1383             // characteristics when all Providers have been located.
1384             return Spliterator.ORDERED;
1385         }
1386 
1387         @Override
1388         public long estimateSize() {
1389             return Long.MAX_VALUE;
1390         }
1391     }
1392 
1393     /**
1394      * Creates a new service loader for the given service type, class
1395      * loader, and caller.
1396      *
1397      * @param  <S> the class of the service type
1398      *
1399      * @param  service
1400      *         The interface or abstract class representing the service
1401      *
1402      * @param  loader
1403      *         The class loader to be used to load provider-configuration files
1404      *         and provider classes, or <tt>null</tt> if the system class
1405      *         loader (or, failing that, the bootstrap class loader) is to be
1406      *         used
1407      *
1408      * @param  callerModule
1409      *         The caller's module for which a new service loader is created
1410      *
1411      * @return A new service loader
1412      */
1413     static <S> ServiceLoader<S> load(Class<S> service,
1414                                      ClassLoader loader,
1415                                      Module callerModule)
1416     {
1417         return new ServiceLoader<>(callerModule, service, loader);
1418     }
1419 
1420     /**
1421      * Creates a new service loader for the given service type and class
1422      * loader.
1423      *
1424      * @param  <S> the class of the service type
1425      *
1426      * @param  service
1427      *         The interface or abstract class representing the service
1428      *
1429      * @param  loader
1430      *         The class loader to be used to load provider-configuration files
1431      *         and provider classes, or {@code null} if the system class
1432      *         loader (or, failing that, the bootstrap class loader) is to be
1433      *         used
1434      *
1435      * @return A new service loader
1436      *
1437      * @throws ServiceConfigurationError
1438      *         if the service type is not accessible to the caller or the
1439      *         caller is in an explicit module and its module descriptor does
1440      *         not declare that it uses {@code service}
1441      *
1442      * @revised 9
1443      * @spec JPMS
1444      */
1445     @CallerSensitive
1446     public static <S> ServiceLoader<S> load(Class<S> service,
1447                                             ClassLoader loader)
1448     {
1449         return new ServiceLoader<>(Reflection.getCallerClass(), service, loader);
1450     }
1451 
1452     /**
1453      * Creates a new service loader for the given service type, using the
1454      * current thread's {@linkplain java.lang.Thread#getContextClassLoader
1455      * context class loader}.
1456      *
1457      * <p> An invocation of this convenience method of the form
1458      * <pre>{@code
1459      * ServiceLoader.load(service)
1460      * }</pre>
1461      *
1462      * is equivalent to
1463      *
1464      * <pre>{@code
1465      * ServiceLoader.load(service, Thread.currentThread().getContextClassLoader())
1466      * }</pre>
1467      *
1468      * @apiNote Service loader objects obtained with this method should not be
1469      * cached VM-wide. For example, different applications in the same VM may
1470      * have different thread context class loaders. A lookup by one application
1471      * may locate a service provider that is only visible via its thread
1472      * context class loader and so is not suitable to be located by the other
1473      * application. Memory leaks can also arise. A thread local may be suited
1474      * to some applications.
1475      *
1476      * @param  <S> the class of the service type
1477      *
1478      * @param  service
1479      *         The interface or abstract class representing the service
1480      *
1481      * @return A new service loader
1482      *
1483      * @throws ServiceConfigurationError
1484      *         if the service type is not accessible to the caller or the
1485      *         caller is in an explicit module and its module descriptor does
1486      *         not declare that it uses {@code service}
1487      *
1488      * @revised 9
1489      * @spec JPMS
1490      */
1491     @CallerSensitive
1492     public static <S> ServiceLoader<S> load(Class<S> service) {
1493         ClassLoader cl = Thread.currentThread().getContextClassLoader();
1494         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1495     }
1496 
1497     /**
1498      * Creates a new service loader for the given service type, using the
1499      * {@linkplain ClassLoader#getPlatformClassLoader() platform class loader}.
1500      *
1501      * <p> This convenience method is equivalent to: </p>
1502      *
1503      * <pre>{@code
1504      * ServiceLoader.load(service, ClassLoader.getPlatformClassLoader())
1505      * }</pre>
1506      *
1507      * <p> This method is intended for use when only installed providers are
1508      * desired.  The resulting service will only find and load providers that
1509      * have been installed into the current Java virtual machine; providers on
1510      * the application's module path or class path will be ignored.
1511      *
1512      * @param  <S> the class of the service type
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      * @revised 9
1525      * @spec JPMS
1526      */
1527     @CallerSensitive
1528     public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
1529         ClassLoader cl = ClassLoader.getPlatformClassLoader();
1530         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1531     }
1532 
1533     /**
1534      * Creates a new service loader for the given service type that loads
1535      * service providers from modules in the given {@code Layer} and its
1536      * ancestors.
1537      *
1538      * @apiNote Unlike the other load methods defined here, the service type
1539      * is the second parameter. The reason for this is to avoid source
1540      * compatibility issues for code that uses {@code load(S, null)}.
1541      *
1542      * @param  <S> the class of the service type
1543      *
1544      * @param  layer
1545      *         The module Layer
1546      *
1547      * @param  service
1548      *         The interface or abstract class representing the service
1549      *
1550      * @return A new service loader
1551      *
1552      * @throws ServiceConfigurationError
1553      *         if the service type is not accessible to the caller or the
1554      *         caller is in an explicit module and its module descriptor does
1555      *         not declare that it uses {@code service}
1556      *
1557      * @since 9
1558      * @spec JPMS
1559      */
1560     @CallerSensitive
1561     public static <S> ServiceLoader<S> load(Layer layer, Class<S> service) {
1562         return new ServiceLoader<>(Reflection.getCallerClass(), layer, service);
1563     }
1564 
1565     /**
1566      * Load the first available provider of this loader's service. This
1567      * convenience method is equivalent to invoking the {@link #iterator()
1568      * iterator()} method and obtaining the first element. It therefore
1569      * returns the first element from the provider cache if possible, it
1570      * otherwise attempts to load and instantiate the first provider.
1571      *
1572      * <p> The following example loads the first available provider. If there
1573      * are no providers deployed then it uses a default implementation.
1574      * <pre>{@code
1575      *    CodecSet provider =
1576      *        ServiceLoader.load(CodecSet.class).findFirst().orElse(DEFAULT_CODECSET);
1577      * }</pre>
1578      * @return The first provider or empty {@code Optional} if no providers
1579      *         are located
1580      *
1581      * @throws ServiceConfigurationError
1582      *         If a provider class cannot be loaded, doesn't have the
1583      *         appropriate static factory method or constructor, can't be
1584      *         assigned to the service type, or if any other kind of exception
1585      *         or error is thrown when locating or instantiating the provider.
1586      *
1587      * @since 9
1588      * @spec JPMS
1589      */
1590     public Optional<S> findFirst() {
1591         Iterator<S> iterator = iterator();
1592         if (iterator.hasNext()) {
1593             return Optional.of(iterator.next());
1594         } else {
1595             return Optional.empty();
1596         }
1597     }
1598 
1599     /**
1600      * Clear this loader's provider cache so that all providers will be
1601      * reloaded.
1602      *
1603      * <p> After invoking this method, subsequent invocations of the {@link
1604      * #iterator() iterator} or {@link #stream() stream} methods will lazily
1605      * look up providers (and instantiate in the case of {@code iterator})
1606      * from scratch, just as is done by a newly-created loader.
1607      *
1608      * <p> This method is intended for use in situations in which new providers
1609      * can be installed into a running Java virtual machine.
1610      */
1611     public void reload() {
1612         lookupIterator1 = null;
1613         instantiatedProviders.clear();
1614 
1615         lookupIterator2 = null;
1616         loadedProviders.clear();
1617         loadedAllProviders = false;
1618 
1619         // increment count to allow CME be thrown
1620         reloadCount++;
1621     }
1622 
1623     /**
1624      * Returns a string describing this service.
1625      *
1626      * @return  A descriptive string
1627      */
1628     public String toString() {
1629         return "java.util.ServiceLoader[" + service.getName() + "]";
1630     }
1631 
1632 }