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 Set<String> providerNames = new HashSet<>(); // to avoid duplicates 1011 Enumeration<URL> configs; 1012 Iterator<String> pending; 1013 Class<?> nextClass; 1014 String nextErrorMessage; // when hasNext fails with CNFE 1015 1016 LazyClassPathLookupIterator() { } 1017 1018 /** 1019 * Parse a single line from the given configuration file, adding the 1020 * name on the line to set of names if not already seen. 1021 */ 1022 private int parseLine(URL u, BufferedReader r, int lc, Set<String> names) 1023 throws IOException 1024 { 1025 String ln = r.readLine(); 1026 if (ln == null) { 1027 return -1; 1028 } 1029 int ci = ln.indexOf('#'); 1030 if (ci >= 0) ln = ln.substring(0, ci); 1031 ln = ln.trim(); 1032 int n = ln.length(); 1033 if (n != 0) { 1034 if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0)) 1035 fail(service, u, lc, "Illegal configuration-file syntax"); 1036 int cp = ln.codePointAt(0); 1037 if (!Character.isJavaIdentifierStart(cp)) 1038 fail(service, u, lc, "Illegal provider-class name: " + ln); 1039 int start = Character.charCount(cp); 1040 for (int i = start; i < n; i += Character.charCount(cp)) { 1041 cp = ln.codePointAt(i); 1042 if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) 1043 fail(service, u, lc, "Illegal provider-class name: " + ln); 1044 } 1045 if (providerNames.add(ln)) { 1046 names.add(ln); 1047 } 1048 } 1049 return lc + 1; 1050 } 1051 1052 /** 1053 * Parse the content of the given URL as a provider-configuration file. 1054 */ 1055 private Iterator<String> parse(URL u) { 1056 Set<String> names = new LinkedHashSet<>(); // preserve insertion order 1057 try { 1058 URLConnection uc = u.openConnection(); 1059 uc.setUseCaches(false); 1060 try (InputStream in = uc.getInputStream(); 1061 BufferedReader r 1062 = new BufferedReader(new InputStreamReader(in, "utf-8"))) 1063 { 1064 int lc = 1; 1065 while ((lc = parseLine(u, r, lc, names)) >= 0); 1066 } 1067 } catch (IOException x) { 1068 fail(service, "Error accessing configuration file", x); 1069 } 1070 return names.iterator(); 1071 } 1072 1073 private boolean hasNextService() { 1074 if (nextClass != null || nextErrorMessage != null) { 1075 return true; 1076 } 1077 1078 Class<?> clazz; 1079 do { 1080 if (configs == null) { 1081 try { 1082 String fullName = PREFIX + service.getName(); 1083 if (loader == null) { 1084 configs = ClassLoader.getSystemResources(fullName); 1085 } else if (loader == ClassLoaders.platformClassLoader()) { 1086 // The platform classloader doesn't have a class path, 1087 // but the boot loader might. 1088 if (BootLoader.hasClassPath()) { 1089 configs = BootLoader.findResources(fullName); 1090 } else { 1091 configs = Collections.emptyEnumeration(); 1092 } 1093 } else { 1094 configs = loader.getResources(fullName); 1095 } 1096 } catch (IOException x) { 1097 fail(service, "Error locating configuration files", x); 1098 } 1099 } 1100 while ((pending == null) || !pending.hasNext()) { 1101 if (!configs.hasMoreElements()) { 1102 return false; 1103 } 1104 pending = parse(configs.nextElement()); 1105 } 1106 String cn = pending.next(); 1107 try { 1108 clazz = Class.forName(cn, false, loader); 1109 } catch (ClassNotFoundException x) { 1110 // don't throw SCE here to long standing behavior 1111 nextErrorMessage = "Provider " + cn + " not found"; 1112 return true; 1113 } 1114 1115 } while (clazz.getModule().isNamed()); // ignore if in named module 1116 1117 nextClass = clazz; 1118 return true; 1119 } 1120 1121 private Provider<T> nextService() { 1122 if (!hasNextService()) 1123 throw new NoSuchElementException(); 1124 1125 // throw any SCE with error recorded by hasNext 1126 if (nextErrorMessage != null) { 1127 String msg = nextErrorMessage; 1128 nextErrorMessage = null; 1129 fail(service, msg); 1130 } 1131 1132 // return next provider 1133 Class<?> clazz = nextClass; 1134 nextClass = null; 1135 return new ProviderImpl<T>(service, clazz, acc); 1136 } 1137 1138 @Override 1139 public boolean hasNext() { 1140 if (acc == null) { 1141 return hasNextService(); 1142 } else { 1143 PrivilegedAction<Boolean> action = new PrivilegedAction<>() { 1144 public Boolean run() { return hasNextService(); } 1145 }; 1146 return AccessController.doPrivileged(action, acc); 1147 } 1148 } 1149 1150 @Override 1151 public Provider<T> next() { 1152 if (acc == null) { 1153 return nextService(); 1154 } else { 1155 PrivilegedAction<Provider<T>> action = new PrivilegedAction<>() { 1156 public Provider<T> run() { return nextService(); } 1157 }; 1158 return AccessController.doPrivileged(action, acc); 1159 } 1160 } 1161 } 1162 1163 /** 1164 * Returns a new lookup iterator. 1165 */ 1166 private Iterator<Provider<S>> newLookupIterator() { 1167 assert layer == null || loader == null; 1168 if (layer != null) { 1169 return new LayerLookupIterator<>(); 1170 } else { 1171 Iterator<Provider<S>> first = new ModuleServicesLookupIterator<>(); 1172 Iterator<Provider<S>> second = new LazyClassPathLookupIterator<>(); 1173 return new Iterator<Provider<S>>() { 1174 @Override 1175 public boolean hasNext() { 1176 return (first.hasNext() || second.hasNext()); 1177 } 1178 @Override 1179 public Provider<S> next() { 1180 if (first.hasNext()) { 1181 return first.next(); 1182 } else if (second.hasNext()) { 1183 return second.next(); 1184 } else { 1185 throw new NoSuchElementException(); 1186 } 1187 } 1188 }; 1189 } 1190 } 1191 1192 /** 1193 * Lazily load and instantiate the available providers of this loader's 1194 * service. 1195 * 1196 * <p> The iterator returned by this method first yields all of the 1197 * elements of the provider cache, in the order that they were loaded. 1198 * It then lazily loads and instantiates any remaining providers, 1199 * adding each one to the cache in turn. 1200 * 1201 * <p> To achieve laziness the actual work of locating and instantiating 1202 * providers must be done by the iterator itself. Its {@link 1203 * java.util.Iterator#hasNext hasNext} and {@link java.util.Iterator#next 1204 * next} methods can therefore throw a {@link ServiceConfigurationError} 1205 * if a provider class cannot be loaded, doesn't have an appropriate static 1206 * factory method or constructor, can't be assigned to the service type or 1207 * if any other kind of exception or error is thrown as the next provider 1208 * is located and instantiated. To write robust code it is only necessary 1209 * to catch {@link ServiceConfigurationError} when using a service iterator. 1210 * 1211 * <p> If such an error is thrown then subsequent invocations of the 1212 * iterator will make a best effort to locate and instantiate the next 1213 * available provider, but in general such recovery cannot be guaranteed. 1214 * 1215 * <blockquote style="font-size: smaller; line-height: 1.2"><span 1216 * style="padding-right: 1em; font-weight: bold">Design Note</span> 1217 * Throwing an error in these cases may seem extreme. The rationale for 1218 * this behavior is that a malformed provider-configuration file, like a 1219 * malformed class file, indicates a serious problem with the way the Java 1220 * virtual machine is configured or is being used. As such it is 1221 * preferable to throw an error rather than try to recover or, even worse, 1222 * fail silently.</blockquote> 1223 * 1224 * <p> If this loader's provider caches are cleared by invoking the {@link 1225 * #reload() reload} method then existing iterators for this service 1226 * loader should be discarded. 1227 * The {@link java.util.Iterator#hasNext() hasNext} and {@link 1228 * java.util.Iterator#next() next} methods of the iterator throw {@link 1229 * java.util.ConcurrentModificationException ConcurrentModificationException} 1230 * if used after the provider cache has been cleared. 1231 * 1232 * <p> The iterator returned by this method does not support removal. 1233 * Invoking its {@link java.util.Iterator#remove() remove} method will 1234 * cause an {@link UnsupportedOperationException} to be thrown. 1235 * 1236 * @return An iterator that lazily loads providers for this loader's 1237 * service 1238 * 1239 * @revised 9 1240 * @spec JPMS 1241 */ 1242 public Iterator<S> iterator() { 1243 1244 // create lookup iterator if needed 1245 if (lookupIterator1 == null) { 1246 lookupIterator1 = newLookupIterator(); 1247 } 1248 1249 return new Iterator<S>() { 1250 1251 // record reload count 1252 final int expectedReloadCount = ServiceLoader.this.reloadCount; 1253 1254 // index into the cached providers list 1255 int index; 1256 1257 /** 1258 * Throws ConcurrentModificationException if the list of cached 1259 * providers has been cleared by reload. 1260 */ 1261 private void checkReloadCount() { 1262 if (ServiceLoader.this.reloadCount != expectedReloadCount) 1263 throw new ConcurrentModificationException(); 1264 } 1265 1266 @Override 1267 public boolean hasNext() { 1268 checkReloadCount(); 1269 if (index < instantiatedProviders.size()) 1270 return true; 1271 return lookupIterator1.hasNext(); 1272 } 1273 1274 @Override 1275 public S next() { 1276 checkReloadCount(); 1277 S next; 1278 if (index < instantiatedProviders.size()) { 1279 next = instantiatedProviders.get(index); 1280 } else { 1281 next = lookupIterator1.next().get(); 1282 instantiatedProviders.add(next); 1283 } 1284 index++; 1285 return next; 1286 } 1287 1288 }; 1289 } 1290 1291 /** 1292 * Returns a stream that lazily loads the available providers of this 1293 * loader's service. The stream elements are of type {@link Provider 1294 * Provider}, the {@code Provider}'s {@link Provider#get() get} method 1295 * must be invoked to get or instantiate the provider. 1296 * 1297 * <p> When processing the stream then providers that were previously 1298 * loaded by stream operations are processed first, in load order. It then 1299 * lazily loads any remaining providers. If a provider class cannot be 1300 * loaded, can't be assigned to the service type, or some other error is 1301 * thrown when locating the provider then it is wrapped with a {@code 1302 * ServiceConfigurationError} and thrown by whatever method caused the 1303 * provider to be loaded. </p> 1304 * 1305 * <p> If this loader's provider caches are cleared by invoking the {@link 1306 * #reload() reload} method then existing streams for this service loader 1307 * should be discarded. The returned stream's source {@code Spliterator} is 1308 * <em>fail-fast</em> and will throw {@link ConcurrentModificationException} 1309 * if the provider cache has been cleared. </p> 1310 * 1311 * <p> The following examples demonstrate usage. The first example 1312 * creates a stream of providers, the second example is the same except 1313 * that it sorts the providers by provider class name (and so locate all 1314 * providers). 1315 * <pre>{@code 1316 * Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class) 1317 * .stream() 1318 * .map(Provider::get); 1319 * 1320 * Stream<CodecSet> providers = ServiceLoader.load(CodecSet.class) 1321 * .stream() 1322 * .sorted(Comparator.comparing(p -> p.type().getName())) 1323 * .map(Provider::get); 1324 * }</pre> 1325 * 1326 * @return A stream that lazily loads providers for this loader's service 1327 * 1328 * @since 9 1329 * @spec JPMS 1330 */ 1331 public Stream<Provider<S>> stream() { 1332 // use cached providers as the source when all providers loaded 1333 if (loadedAllProviders) { 1334 return loadedProviders.stream(); 1335 } 1336 1337 // create lookup iterator if needed 1338 if (lookupIterator2 == null) { 1339 lookupIterator2 = newLookupIterator(); 1340 } 1341 1342 // use lookup iterator and cached providers as source 1343 Spliterator<Provider<S>> s = new ProviderSpliterator<>(lookupIterator2); 1344 return StreamSupport.stream(s, false); 1345 } 1346 1347 private class ProviderSpliterator<T> implements Spliterator<Provider<T>> { 1348 final int expectedReloadCount = ServiceLoader.this.reloadCount; 1349 final Iterator<Provider<T>> iterator; 1350 int index; 1351 1352 ProviderSpliterator(Iterator<Provider<T>> iterator) { 1353 this.iterator = iterator; 1354 } 1355 1356 @Override 1357 public Spliterator<Provider<T>> trySplit() { 1358 return null; 1359 } 1360 1361 @Override 1362 @SuppressWarnings("unchecked") 1363 public boolean tryAdvance(Consumer<? super Provider<T>> action) { 1364 if (ServiceLoader.this.reloadCount != expectedReloadCount) 1365 throw new ConcurrentModificationException(); 1366 Provider<T> next = null; 1367 if (index < loadedProviders.size()) { 1368 next = (Provider<T>) loadedProviders.get(index++); 1369 } else if (iterator.hasNext()) { 1370 next = iterator.next(); 1371 } else { 1372 loadedAllProviders = true; 1373 } 1374 if (next != null) { 1375 action.accept(next); 1376 return true; 1377 } else { 1378 return false; 1379 } 1380 } 1381 1382 @Override 1383 public int characteristics() { 1384 // not IMMUTABLE as structural interference possible 1385 // not NOTNULL so that the characteristics are a subset of the 1386 // characteristics when all Providers have been located. 1387 return Spliterator.ORDERED; 1388 } 1389 1390 @Override 1391 public long estimateSize() { 1392 return Long.MAX_VALUE; 1393 } 1394 } 1395 1396 /** 1397 * Creates a new service loader for the given service type, class 1398 * loader, and caller. 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 <tt>null</tt> if the system class 1408 * loader (or, failing that, the bootstrap class loader) is to be 1409 * used 1410 * 1411 * @param callerModule 1412 * The caller's module for which a new service loader is created 1413 * 1414 * @return A new service loader 1415 */ 1416 static <S> ServiceLoader<S> load(Class<S> service, 1417 ClassLoader loader, 1418 Module callerModule) 1419 { 1420 return new ServiceLoader<>(callerModule, service, loader); 1421 } 1422 1423 /** 1424 * Creates a new service loader for the given service type and class 1425 * loader. 1426 * 1427 * @param <S> the class of the service type 1428 * 1429 * @param service 1430 * The interface or abstract class representing the service 1431 * 1432 * @param loader 1433 * The class loader to be used to load provider-configuration files 1434 * and provider classes, or {@code null} if the system class 1435 * loader (or, failing that, the bootstrap class loader) is to be 1436 * used 1437 * 1438 * @return A new service loader 1439 * 1440 * @throws ServiceConfigurationError 1441 * if the service type is not accessible to the caller or the 1442 * caller is in an explicit module and its module descriptor does 1443 * not declare that it uses {@code service} 1444 * 1445 * @revised 9 1446 * @spec JPMS 1447 */ 1448 @CallerSensitive 1449 public static <S> ServiceLoader<S> load(Class<S> service, 1450 ClassLoader loader) 1451 { 1452 return new ServiceLoader<>(Reflection.getCallerClass(), service, loader); 1453 } 1454 1455 /** 1456 * Creates a new service loader for the given service type, using the 1457 * current thread's {@linkplain java.lang.Thread#getContextClassLoader 1458 * context class loader}. 1459 * 1460 * <p> An invocation of this convenience method of the form 1461 * <pre>{@code 1462 * ServiceLoader.load(service) 1463 * }</pre> 1464 * 1465 * is equivalent to 1466 * 1467 * <pre>{@code 1468 * ServiceLoader.load(service, Thread.currentThread().getContextClassLoader()) 1469 * }</pre> 1470 * 1471 * @apiNote Service loader objects obtained with this method should not be 1472 * cached VM-wide. For example, different applications in the same VM may 1473 * have different thread context class loaders. A lookup by one application 1474 * may locate a service provider that is only visible via its thread 1475 * context class loader and so is not suitable to be located by the other 1476 * application. Memory leaks can also arise. A thread local may be suited 1477 * to some applications. 1478 * 1479 * @param <S> the class of the service type 1480 * 1481 * @param service 1482 * The interface or abstract class representing the service 1483 * 1484 * @return A new service loader 1485 * 1486 * @throws ServiceConfigurationError 1487 * if the service type is not accessible to the caller or the 1488 * caller is in an explicit module and its module descriptor does 1489 * not declare that it uses {@code service} 1490 * 1491 * @revised 9 1492 * @spec JPMS 1493 */ 1494 @CallerSensitive 1495 public static <S> ServiceLoader<S> load(Class<S> service) { 1496 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 1497 return new ServiceLoader<>(Reflection.getCallerClass(), service, cl); 1498 } 1499 1500 /** 1501 * Creates a new service loader for the given service type, using the 1502 * {@linkplain ClassLoader#getPlatformClassLoader() platform class loader}. 1503 * 1504 * <p> This convenience method is equivalent to: </p> 1505 * 1506 * <pre>{@code 1507 * ServiceLoader.load(service, ClassLoader.getPlatformClassLoader()) 1508 * }</pre> 1509 * 1510 * <p> This method is intended for use when only installed providers are 1511 * desired. The resulting service will only find and load providers that 1512 * have been installed into the current Java virtual machine; providers on 1513 * the application's module path or class path will be ignored. 1514 * 1515 * @param <S> the class of the service type 1516 * 1517 * @param service 1518 * The interface or abstract class representing the service 1519 * 1520 * @return A new service loader 1521 * 1522 * @throws ServiceConfigurationError 1523 * if the service type is not accessible to the caller or the 1524 * caller is in an explicit module and its module descriptor does 1525 * not declare that it uses {@code service} 1526 * 1527 * @revised 9 1528 * @spec JPMS 1529 */ 1530 @CallerSensitive 1531 public static <S> ServiceLoader<S> loadInstalled(Class<S> service) { 1532 ClassLoader cl = ClassLoader.getPlatformClassLoader(); 1533 return new ServiceLoader<>(Reflection.getCallerClass(), service, cl); 1534 } 1535 1536 /** 1537 * Creates a new service loader for the given service type that loads 1538 * service providers from modules in the given {@code Layer} and its 1539 * ancestors. 1540 * 1541 * @apiNote Unlike the other load methods defined here, the service type 1542 * is the second parameter. The reason for this is to avoid source 1543 * compatibility issues for code that uses {@code load(S, null)}. 1544 * 1545 * @param <S> the class of the service type 1546 * 1547 * @param layer 1548 * The module Layer 1549 * 1550 * @param service 1551 * The interface or abstract class representing the service 1552 * 1553 * @return A new service loader 1554 * 1555 * @throws ServiceConfigurationError 1556 * if the service type is not accessible to the caller or the 1557 * caller is in an explicit module and its module descriptor does 1558 * not declare that it uses {@code service} 1559 * 1560 * @since 9 1561 * @spec JPMS 1562 */ 1563 @CallerSensitive 1564 public static <S> ServiceLoader<S> load(Layer layer, Class<S> service) { 1565 return new ServiceLoader<>(Reflection.getCallerClass(), layer, service); 1566 } 1567 1568 /** 1569 * Load the first available provider of this loader's service. This 1570 * convenience method is equivalent to invoking the {@link #iterator() 1571 * iterator()} method and obtaining the first element. It therefore 1572 * returns the first element from the provider cache if possible, it 1573 * otherwise attempts to load and instantiate the first provider. 1574 * 1575 * <p> The following example loads the first available provider. If there 1576 * are no providers deployed then it uses a default implementation. 1577 * <pre>{@code 1578 * CodecSet provider = 1579 * ServiceLoader.load(CodecSet.class).findFirst().orElse(DEFAULT_CODECSET); 1580 * }</pre> 1581 * @return The first provider or empty {@code Optional} if no providers 1582 * are located 1583 * 1584 * @throws ServiceConfigurationError 1585 * If a provider class cannot be loaded, doesn't have the 1586 * appropriate static factory method or constructor, can't be 1587 * assigned to the service type, or if any other kind of exception 1588 * or error is thrown when locating or instantiating the provider. 1589 * 1590 * @since 9 1591 * @spec JPMS 1592 */ 1593 public Optional<S> findFirst() { 1594 Iterator<S> iterator = iterator(); 1595 if (iterator.hasNext()) { 1596 return Optional.of(iterator.next()); 1597 } else { 1598 return Optional.empty(); 1599 } 1600 } 1601 1602 /** 1603 * Clear this loader's provider cache so that all providers will be 1604 * reloaded. 1605 * 1606 * <p> After invoking this method, subsequent invocations of the {@link 1607 * #iterator() iterator} or {@link #stream() stream} methods will lazily 1608 * look up providers (and instantiate in the case of {@code iterator}) 1609 * from scratch, just as is done by a newly-created loader. 1610 * 1611 * <p> This method is intended for use in situations in which new providers 1612 * can be installed into a running Java virtual machine. 1613 */ 1614 public void reload() { 1615 lookupIterator1 = null; 1616 instantiatedProviders.clear(); 1617 1618 lookupIterator2 = null; 1619 loadedProviders.clear(); 1620 loadedAllProviders = false; 1621 1622 // increment count to allow CME be thrown 1623 reloadCount++; 1624 } 1625 1626 /** 1627 * Returns a string describing this service. 1628 * 1629 * @return A descriptive string 1630 */ 1631 public String toString() { 1632 return "java.util.ServiceLoader[" + service.getName() + "]"; 1633 } 1634 1635 }