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