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