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