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 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.Method; 35 import java.lang.reflect.Modifier; 36 import java.net.URL; 37 import java.net.URLConnection; 38 import java.security.AccessControlContext; 39 import java.security.AccessController; 40 import java.security.PrivilegedAction; 41 import java.security.PrivilegedActionException; 42 import java.security.PrivilegedExceptionAction; 43 import java.util.function.Consumer; 44 import java.util.function.Supplier; 45 import java.util.stream.Stream; 46 import java.util.stream.StreamSupport; 47 48 import jdk.internal.loader.BootLoader; 49 import jdk.internal.loader.ClassLoaders; 50 import jdk.internal.misc.JavaLangAccess; 51 import jdk.internal.misc.SharedSecrets; 52 import jdk.internal.misc.VM; 53 import jdk.internal.module.ServicesCatalog; 54 import jdk.internal.module.ServicesCatalog.ServiceProvider; 55 import jdk.internal.reflect.CallerSensitive; 56 import 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 390 public 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 (Throwable x) { 751 if (x instanceof PrivilegedActionException) 752 x = x.getCause(); 753 exc = x; 754 } 755 } 756 if (exc != null) { 757 if (exc instanceof InvocationTargetException) 758 exc = exc.getCause(); 759 fail(service, factoryMethod + " failed", exc); 760 } 761 if (result == null) { 762 fail(service, factoryMethod + " returned null"); 763 } 764 @SuppressWarnings("unchecked") 765 S p = (S) result; 766 return p; 767 } 768 769 /** 770 * Invokes Constructor::newInstance to instantiate a provider. When running 771 * with a security manager then the constructor runs with permissions that 772 * are restricted by the security context of whatever created this loader. 773 */ 774 private S newInstance() { 775 S p = null; 776 Throwable exc = null; 777 if (acc == null) { 778 try { 779 p = ctor.newInstance(); 780 } catch (Throwable x) { 781 exc = x; 782 } 783 } else { 784 PrivilegedExceptionAction<S> pa = new PrivilegedExceptionAction<>() { 785 @Override 786 public S run() throws Exception { 787 return ctor.newInstance(); 788 } 789 }; 790 // invoke constructor with permissions restricted by acc 791 try { 792 p = AccessController.doPrivileged(pa, acc); 793 } catch (Throwable x) { 794 if (x instanceof PrivilegedActionException) 795 x = x.getCause(); 796 exc = x; 797 } 798 } 799 if (exc != null) { 800 if (exc instanceof InvocationTargetException) 801 exc = exc.getCause(); 802 String cn = ctor.getDeclaringClass().getName(); 803 fail(service, 804 "Provider " + cn + " could not be instantiated", exc); 805 } 806 return p; 807 } 808 809 // For now, equals/hashCode uses the access control context to ensure 810 // that two Providers created with different contexts are not equal 811 // when running with a security manager. 812 813 @Override 814 public int hashCode() { 815 return Objects.hash(service, type, acc); 816 } 817 818 @Override 819 public boolean equals(Object ob) { 820 if (!(ob instanceof ProviderImpl)) 821 return false; 822 @SuppressWarnings("unchecked") 823 ProviderImpl<?> that = (ProviderImpl<?>)ob; 824 return this.service == that.service 825 && this.type == that.type 826 && Objects.equals(this.acc, that.acc); 827 } 828 } 829 830 /** 831 * Loads a service provider in a module. 832 * 833 * Returns {@code null} if the service provider's module doesn't read 834 * the module with the service type. 835 * 836 * @throws ServiceConfigurationError if the class cannot be loaded or 837 * isn't the expected sub-type (or doesn't define a provider 838 * factory method that returns the expected type) 839 */ 840 private Provider<S> loadProvider(ServiceProvider provider) { 841 Module module = provider.module(); 842 if (!module.canRead(service.getModule())) { 843 // module does not read the module with the service type 844 return null; 845 } 846 847 String cn = provider.providerName(); 848 Class<?> clazz = null; 849 if (acc == null) { 850 try { 851 clazz = Class.forName(module, cn); 852 } catch (LinkageError e) { 853 fail(service, "Unable to load " + cn, e); 854 } 855 } else { 856 PrivilegedExceptionAction<Class<?>> pa = () -> Class.forName(module, cn); 857 try { 858 clazz = AccessController.doPrivileged(pa); 859 } catch (Throwable x) { 860 if (x instanceof PrivilegedActionException) 861 x = x.getCause(); 862 fail(service, "Unable to load " + cn, x); 863 return null; 864 } 865 } 866 if (clazz == null) { 867 fail(service, "Provider " + cn + " not found"); 868 } 869 870 int mods = clazz.getModifiers(); 871 if (!Modifier.isPublic(mods)) { 872 fail(service, clazz + " is not public"); 873 } 874 875 // if provider in explicit module then check for static factory method 876 if (inExplicitModule(clazz)) { 877 Method factoryMethod = findStaticProviderMethod(clazz); 878 if (factoryMethod != null) { 879 Class<?> returnType = factoryMethod.getReturnType(); 880 if (!service.isAssignableFrom(returnType)) { 881 fail(service, factoryMethod + " return type not a subtype"); 882 } 883 884 @SuppressWarnings("unchecked") 885 Class<? extends S> type = (Class<? extends S>) returnType; 886 return new ProviderImpl<S>(service, type, factoryMethod, acc); 887 } 888 } 889 890 // no factory method so must be a subtype 891 if (!service.isAssignableFrom(clazz)) { 892 fail(service, clazz.getName() + " not a subtype"); 893 } 894 895 @SuppressWarnings("unchecked") 896 Class<? extends S> type = (Class<? extends S>) clazz; 897 @SuppressWarnings("unchecked") 898 Constructor<? extends S> ctor = (Constructor<? extends S> ) getConstructor(clazz); 899 return new ProviderImpl<S>(service, type, ctor, acc); 900 } 901 902 /** 903 * Implements lazy service provider lookup of service providers that 904 * are provided by modules in a module layer (or parent layers) 905 */ 906 private final class LayerLookupIterator<T> 907 implements Iterator<Provider<T>> 908 { 909 Deque<ModuleLayer> stack = new ArrayDeque<>(); 910 Set<ModuleLayer> visited = new HashSet<>(); 911 Iterator<ServiceProvider> iterator; 912 913 Provider<T> nextProvider; 914 ServiceConfigurationError nextError; 915 916 LayerLookupIterator() { 917 visited.add(layer); 918 stack.push(layer); 919 } 920 921 private Iterator<ServiceProvider> providers(ModuleLayer layer) { 922 ServicesCatalog catalog = LANG_ACCESS.getServicesCatalog(layer); 923 return catalog.findServices(serviceName).iterator(); 924 } 925 926 @Override 927 public boolean hasNext() { 928 while (nextProvider == null && nextError == null) { 929 // get next provider to load 930 while (iterator == null || !iterator.hasNext()) { 931 // next layer (DFS order) 932 if (stack.isEmpty()) 933 return false; 934 935 ModuleLayer layer = stack.pop(); 936 List<ModuleLayer> parents = layer.parents(); 937 for (int i = parents.size() - 1; i >= 0; i--) { 938 ModuleLayer parent = parents.get(i); 939 if (!visited.contains(parent)) { 940 visited.add(parent); 941 stack.push(parent); 942 } 943 } 944 iterator = providers(layer); 945 } 946 947 // attempt to load provider 948 ServiceProvider provider = iterator.next(); 949 try { 950 @SuppressWarnings("unchecked") 951 Provider<T> next = (Provider<T>) loadProvider(provider); 952 nextProvider = next; 953 } catch (ServiceConfigurationError e) { 954 nextError = e; 955 } 956 } 957 return true; 958 } 959 960 @Override 961 public Provider<T> next() { 962 if (!hasNext()) 963 throw new NoSuchElementException(); 964 965 Provider<T> provider = nextProvider; 966 if (provider != null) { 967 nextProvider = null; 968 return provider; 969 } else { 970 ServiceConfigurationError e = nextError; 971 assert e != null; 972 nextError = null; 973 throw e; 974 } 975 } 976 } 977 978 /** 979 * Implements lazy service provider lookup of service providers that 980 * are provided by modules defined to a class loader or to modules in 981 * layers with a module defined to the class loader. 982 */ 983 private final class ModuleServicesLookupIterator<T> 984 implements Iterator<Provider<T>> 985 { 986 ClassLoader currentLoader; 987 Iterator<ServiceProvider> iterator; 988 989 Provider<T> nextProvider; 990 ServiceConfigurationError nextError; 991 992 ModuleServicesLookupIterator() { 993 this.currentLoader = loader; 994 this.iterator = iteratorFor(loader); 995 } 996 997 /** 998 * Returns iterator to iterate over the implementations of {@code 999 * service} in the given layer. 1000 */ 1001 private List<ServiceProvider> providers(ModuleLayer layer) { 1002 ServicesCatalog catalog = LANG_ACCESS.getServicesCatalog(layer); 1003 return catalog.findServices(serviceName); 1004 } 1005 1006 /** 1007 * Returns the class loader that a module is defined to 1008 */ 1009 private ClassLoader loaderFor(Module module) { 1010 SecurityManager sm = System.getSecurityManager(); 1011 if (sm == null) { 1012 return module.getClassLoader(); 1013 } else { 1014 PrivilegedAction<ClassLoader> pa = module::getClassLoader; 1015 return AccessController.doPrivileged(pa); 1016 } 1017 } 1018 1019 /** 1020 * Returns an iterator to iterate over the implementations of {@code 1021 * service} in modules defined to the given class loader or in custom 1022 * layers with a module defined to this class loader. 1023 */ 1024 private Iterator<ServiceProvider> iteratorFor(ClassLoader loader) { 1025 // modules defined to the class loader 1026 ServicesCatalog catalog; 1027 if (loader == null) { 1028 catalog = BootLoader.getServicesCatalog(); 1029 } else { 1030 catalog = ServicesCatalog.getServicesCatalogOrNull(loader); 1031 } 1032 List<ServiceProvider> providers; 1033 if (catalog == null) { 1034 providers = List.of(); 1035 } else { 1036 providers = catalog.findServices(serviceName); 1037 } 1038 1039 // modules in layers that define modules to the class loader 1040 ClassLoader platformClassLoader = ClassLoaders.platformClassLoader(); 1041 if (loader == null || loader == platformClassLoader) { 1042 return providers.iterator(); 1043 } else { 1044 List<ServiceProvider> allProviders = new ArrayList<>(providers); 1045 Iterator<ModuleLayer> iterator = LANG_ACCESS.layers(loader).iterator(); 1046 while (iterator.hasNext()) { 1047 ModuleLayer layer = iterator.next(); 1048 for (ServiceProvider sp : providers(layer)) { 1049 ClassLoader l = loaderFor(sp.module()); 1050 if (l != null && l != platformClassLoader) { 1051 allProviders.add(sp); 1052 } 1053 } 1054 } 1055 return allProviders.iterator(); 1056 } 1057 } 1058 1059 @Override 1060 public boolean hasNext() { 1061 while (nextProvider == null && nextError == null) { 1062 // get next provider to load 1063 while (!iterator.hasNext()) { 1064 if (currentLoader == null) { 1065 return false; 1066 } else { 1067 currentLoader = currentLoader.getParent(); 1068 iterator = iteratorFor(currentLoader); 1069 } 1070 } 1071 1072 // attempt to load provider 1073 ServiceProvider provider = iterator.next(); 1074 try { 1075 @SuppressWarnings("unchecked") 1076 Provider<T> next = (Provider<T>) loadProvider(provider); 1077 nextProvider = next; 1078 } catch (ServiceConfigurationError e) { 1079 nextError = e; 1080 } 1081 } 1082 return true; 1083 } 1084 1085 @Override 1086 public Provider<T> next() { 1087 if (!hasNext()) 1088 throw new NoSuchElementException(); 1089 1090 Provider<T> provider = nextProvider; 1091 if (provider != null) { 1092 nextProvider = null; 1093 return provider; 1094 } else { 1095 ServiceConfigurationError e = nextError; 1096 assert e != null; 1097 nextError = null; 1098 throw e; 1099 } 1100 } 1101 } 1102 1103 /** 1104 * Implements lazy service provider lookup where the service providers are 1105 * configured via service configuration files. Service providers in named 1106 * modules are silently ignored by this lookup iterator. 1107 */ 1108 private final class LazyClassPathLookupIterator<T> 1109 implements Iterator<Provider<T>> 1110 { 1111 static final String PREFIX = "META-INF/services/"; 1112 1113 Set<String> providerNames = new HashSet<>(); // to avoid duplicates 1114 Enumeration<URL> configs; 1115 Iterator<String> pending; 1116 1117 Provider<T> nextProvider; 1118 ServiceConfigurationError nextError; 1119 1120 LazyClassPathLookupIterator() { } 1121 1122 /** 1123 * Parse a single line from the given configuration file, adding the 1124 * name on the line to set of names if not already seen. 1125 */ 1126 private int parseLine(URL u, BufferedReader r, int lc, Set<String> names) 1127 throws IOException 1128 { 1129 String ln = r.readLine(); 1130 if (ln == null) { 1131 return -1; 1132 } 1133 int ci = ln.indexOf('#'); 1134 if (ci >= 0) ln = ln.substring(0, ci); 1135 ln = ln.trim(); 1136 int n = ln.length(); 1137 if (n != 0) { 1138 if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0)) 1139 fail(service, u, lc, "Illegal configuration-file syntax"); 1140 int cp = ln.codePointAt(0); 1141 if (!Character.isJavaIdentifierStart(cp)) 1142 fail(service, u, lc, "Illegal provider-class name: " + ln); 1143 int start = Character.charCount(cp); 1144 for (int i = start; i < n; i += Character.charCount(cp)) { 1145 cp = ln.codePointAt(i); 1146 if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) 1147 fail(service, u, lc, "Illegal provider-class name: " + ln); 1148 } 1149 if (providerNames.add(ln)) { 1150 names.add(ln); 1151 } 1152 } 1153 return lc + 1; 1154 } 1155 1156 /** 1157 * Parse the content of the given URL as a provider-configuration file. 1158 */ 1159 private Iterator<String> parse(URL u) { 1160 Set<String> names = new LinkedHashSet<>(); // preserve insertion order 1161 try { 1162 URLConnection uc = u.openConnection(); 1163 uc.setUseCaches(false); 1164 try (InputStream in = uc.getInputStream(); 1165 BufferedReader r 1166 = new BufferedReader(new InputStreamReader(in, "utf-8"))) 1167 { 1168 int lc = 1; 1169 while ((lc = parseLine(u, r, lc, names)) >= 0); 1170 } 1171 } catch (IOException x) { 1172 fail(service, "Error accessing configuration file", x); 1173 } 1174 return names.iterator(); 1175 } 1176 1177 /** 1178 * Loads and returns the next provider class. 1179 */ 1180 private Class<?> nextProviderClass() { 1181 if (configs == null) { 1182 try { 1183 String fullName = PREFIX + service.getName(); 1184 if (loader == null) { 1185 configs = ClassLoader.getSystemResources(fullName); 1186 } else if (loader == ClassLoaders.platformClassLoader()) { 1187 // The platform classloader doesn't have a class path, 1188 // but the boot loader might. 1189 if (BootLoader.hasClassPath()) { 1190 configs = BootLoader.findResources(fullName); 1191 } else { 1192 configs = Collections.emptyEnumeration(); 1193 } 1194 } else { 1195 configs = loader.getResources(fullName); 1196 } 1197 } catch (IOException x) { 1198 fail(service, "Error locating configuration files", x); 1199 } 1200 } 1201 while ((pending == null) || !pending.hasNext()) { 1202 if (!configs.hasMoreElements()) { 1203 return null; 1204 } 1205 pending = parse(configs.nextElement()); 1206 } 1207 String cn = pending.next(); 1208 try { 1209 return Class.forName(cn, false, loader); 1210 } catch (ClassNotFoundException x) { 1211 fail(service, "Provider " + cn + " not found"); 1212 return null; 1213 } 1214 } 1215 1216 @SuppressWarnings("unchecked") 1217 private boolean hasNextService() { 1218 while (nextProvider == null && nextError == null) { 1219 try { 1220 Class<?> clazz = nextProviderClass(); 1221 if (clazz == null) 1222 return false; 1223 1224 if (clazz.getModule().isNamed()) { 1225 // ignore class if in named module 1226 continue; 1227 } 1228 1229 if (service.isAssignableFrom(clazz)) { 1230 Class<? extends S> type = (Class<? extends S>) clazz; 1231 Constructor<? extends S> ctor 1232 = (Constructor<? extends S>)getConstructor(clazz); 1233 ProviderImpl<S> p = new ProviderImpl<S>(service, type, ctor, acc); 1234 nextProvider = (ProviderImpl<T>) p; 1235 } else { 1236 fail(service, clazz.getName() + " not a subtype"); 1237 } 1238 } catch (ServiceConfigurationError e) { 1239 nextError = e; 1240 } 1241 } 1242 return true; 1243 } 1244 1245 private Provider<T> nextService() { 1246 if (!hasNextService()) 1247 throw new NoSuchElementException(); 1248 1249 Provider<T> provider = nextProvider; 1250 if (provider != null) { 1251 nextProvider = null; 1252 return provider; 1253 } else { 1254 ServiceConfigurationError e = nextError; 1255 assert e != null; 1256 nextError = null; 1257 throw e; 1258 } 1259 } 1260 1261 @Override 1262 public boolean hasNext() { 1263 if (acc == null) { 1264 return hasNextService(); 1265 } else { 1266 PrivilegedAction<Boolean> action = new PrivilegedAction<>() { 1267 public Boolean run() { return hasNextService(); } 1268 }; 1269 return AccessController.doPrivileged(action, acc); 1270 } 1271 } 1272 1273 @Override 1274 public Provider<T> next() { 1275 if (acc == null) { 1276 return nextService(); 1277 } else { 1278 PrivilegedAction<Provider<T>> action = new PrivilegedAction<>() { 1279 public Provider<T> run() { return nextService(); } 1280 }; 1281 return AccessController.doPrivileged(action, acc); 1282 } 1283 } 1284 } 1285 1286 /** 1287 * Returns a new lookup iterator. 1288 */ 1289 private Iterator<Provider<S>> newLookupIterator() { 1290 assert layer == null || loader == null; 1291 if (layer != null) { 1292 return new LayerLookupIterator<>(); 1293 } else { 1294 Iterator<Provider<S>> first = new ModuleServicesLookupIterator<>(); 1295 Iterator<Provider<S>> second = new LazyClassPathLookupIterator<>(); 1296 return new Iterator<Provider<S>>() { 1297 @Override 1298 public boolean hasNext() { 1299 return (first.hasNext() || second.hasNext()); 1300 } 1301 @Override 1302 public Provider<S> next() { 1303 if (first.hasNext()) { 1304 return first.next(); 1305 } else if (second.hasNext()) { 1306 return second.next(); 1307 } else { 1308 throw new NoSuchElementException(); 1309 } 1310 } 1311 }; 1312 } 1313 } 1314 1315 /** 1316 * Returns an iterator to lazily load and instantiate the available 1317 * providers of this loader's service. 1318 * 1319 * <p> To achieve laziness the actual work of locating and instantiating 1320 * providers is done by the iterator itself. Its {@link Iterator#hasNext 1321 * hasNext} and {@link Iterator#next next} methods can therefore throw a 1322 * {@link ServiceConfigurationError} for any of the reasons specified in 1323 * the <a href="#errors">Errors</a> section above. To write robust code it 1324 * is only necessary to catch {@code ServiceConfigurationError} when using 1325 * the iterator. If an error is thrown then subsequent invocations of the 1326 * iterator will make a best effort to locate and instantiate the next 1327 * available provider, but in general such recovery cannot be guaranteed. 1328 * 1329 * <p> Caching: The iterator returned by this method first yields all of 1330 * the elements of the provider cache, in the order that they were loaded. 1331 * It then lazily loads and instantiates any remaining service providers, 1332 * adding each one to the cache in turn. If this loader's provider caches are 1333 * cleared by invoking the {@link #reload() reload} method then existing 1334 * iterators for this service loader should be discarded. 1335 * The {@code hasNext} and {@code next} methods of the iterator throw {@link 1336 * java.util.ConcurrentModificationException ConcurrentModificationException} 1337 * if used after the provider cache has been cleared. 1338 * 1339 * <p> The iterator returned by this method does not support removal. 1340 * Invoking its {@link java.util.Iterator#remove() remove} method will 1341 * cause an {@link UnsupportedOperationException} to be thrown. 1342 * 1343 * @apiNote Throwing an error in these cases may seem extreme. The rationale 1344 * for this behavior is that a malformed provider-configuration file, like a 1345 * malformed class file, indicates a serious problem with the way the Java 1346 * virtual machine is configured or is being used. As such it is preferable 1347 * to throw an error rather than try to recover or, even worse, fail silently. 1348 * 1349 * @return An iterator that lazily loads providers for this loader's 1350 * service 1351 * 1352 * @revised 9 1353 * @spec JPMS 1354 */ 1355 public Iterator<S> iterator() { 1356 1357 // create lookup iterator if needed 1358 if (lookupIterator1 == null) { 1359 lookupIterator1 = newLookupIterator(); 1360 } 1361 1362 return new Iterator<S>() { 1363 1364 // record reload count 1365 final int expectedReloadCount = ServiceLoader.this.reloadCount; 1366 1367 // index into the cached providers list 1368 int index; 1369 1370 /** 1371 * Throws ConcurrentModificationException if the list of cached 1372 * providers has been cleared by reload. 1373 */ 1374 private void checkReloadCount() { 1375 if (ServiceLoader.this.reloadCount != expectedReloadCount) 1376 throw new ConcurrentModificationException(); 1377 } 1378 1379 @Override 1380 public boolean hasNext() { 1381 checkReloadCount(); 1382 if (index < instantiatedProviders.size()) 1383 return true; 1384 return lookupIterator1.hasNext(); 1385 } 1386 1387 @Override 1388 public S next() { 1389 checkReloadCount(); 1390 S next; 1391 if (index < instantiatedProviders.size()) { 1392 next = instantiatedProviders.get(index); 1393 } else { 1394 next = lookupIterator1.next().get(); 1395 instantiatedProviders.add(next); 1396 } 1397 index++; 1398 return next; 1399 } 1400 1401 }; 1402 } 1403 1404 /** 1405 * Returns a stream to lazily load available providers of this loader's 1406 * service. The stream elements are of type {@link Provider Provider}, the 1407 * {@code Provider}'s {@link Provider#get() get} method must be invoked to 1408 * get or instantiate the provider. 1409 * 1410 * <p> To achieve laziness the actual work of locating providers is done 1411 * when processing the stream. If a service provider cannot be loaded for any 1412 * of the reasons specified in the <a href="#errors">Errors</a> section 1413 * above then {@link ServiceConfigurationError} is thrown by whatever method 1414 * caused the service provider to be loaded. </p> 1415 * 1416 * <p> Caching: When processing the stream then providers that were previously 1417 * loaded by stream operations are processed first, in load order. It then 1418 * lazily loads any remaining service providers. If this loader's provider 1419 * caches are cleared by invoking the {@link #reload() reload} method then 1420 * existing streams for this service loader should be discarded. The returned 1421 * stream's source {@link Spliterator spliterator} is <em>fail-fast</em> and 1422 * will throw {@link ConcurrentModificationException} if the provider cache 1423 * has been cleared. </p> 1424 * 1425 * <p> The following examples demonstrate usage. The first example creates 1426 * a stream of {@code CodecFactory} objects, the second example is the same 1427 * except that it sorts the providers by provider class name (and so locate 1428 * all providers). 1429 * <pre>{@code 1430 * Stream<CodecFactory> providers = ServiceLoader.load(CodecFactory.class) 1431 * .stream() 1432 * .map(Provider::get); 1433 * 1434 * Stream<CodecFactory> providers = ServiceLoader.load(CodecFactory.class) 1435 * .stream() 1436 * .sorted(Comparator.comparing(p -> p.type().getName())) 1437 * .map(Provider::get); 1438 * }</pre> 1439 * 1440 * @return A stream that lazily loads providers for this loader's service 1441 * 1442 * @since 9 1443 * @spec JPMS 1444 */ 1445 public Stream<Provider<S>> stream() { 1446 // use cached providers as the source when all providers loaded 1447 if (loadedAllProviders) { 1448 return loadedProviders.stream(); 1449 } 1450 1451 // create lookup iterator if needed 1452 if (lookupIterator2 == null) { 1453 lookupIterator2 = newLookupIterator(); 1454 } 1455 1456 // use lookup iterator and cached providers as source 1457 Spliterator<Provider<S>> s = new ProviderSpliterator<>(lookupIterator2); 1458 return StreamSupport.stream(s, false); 1459 } 1460 1461 private class ProviderSpliterator<T> implements Spliterator<Provider<T>> { 1462 final int expectedReloadCount = ServiceLoader.this.reloadCount; 1463 final Iterator<Provider<T>> iterator; 1464 int index; 1465 1466 ProviderSpliterator(Iterator<Provider<T>> iterator) { 1467 this.iterator = iterator; 1468 } 1469 1470 @Override 1471 public Spliterator<Provider<T>> trySplit() { 1472 return null; 1473 } 1474 1475 @Override 1476 @SuppressWarnings("unchecked") 1477 public boolean tryAdvance(Consumer<? super Provider<T>> action) { 1478 if (ServiceLoader.this.reloadCount != expectedReloadCount) 1479 throw new ConcurrentModificationException(); 1480 Provider<T> next = null; 1481 if (index < loadedProviders.size()) { 1482 next = (Provider<T>) loadedProviders.get(index++); 1483 } else if (iterator.hasNext()) { 1484 next = iterator.next(); 1485 loadedProviders.add((Provider<S>)next); 1486 index++; 1487 } else { 1488 loadedAllProviders = true; 1489 } 1490 if (next != null) { 1491 action.accept(next); 1492 return true; 1493 } else { 1494 return false; 1495 } 1496 } 1497 1498 @Override 1499 public int characteristics() { 1500 // not IMMUTABLE as structural interference possible 1501 // not NOTNULL so that the characteristics are a subset of the 1502 // characteristics when all Providers have been located. 1503 return Spliterator.ORDERED; 1504 } 1505 1506 @Override 1507 public long estimateSize() { 1508 return Long.MAX_VALUE; 1509 } 1510 } 1511 1512 /** 1513 * Creates a new service loader for the given service type, class 1514 * loader, and caller. 1515 * 1516 * @param <S> the class of the service type 1517 * 1518 * @param service 1519 * The interface or abstract class representing the service 1520 * 1521 * @param loader 1522 * The class loader to be used to load provider-configuration files 1523 * and provider classes, or {@code null} if the system class 1524 * loader (or, failing that, the bootstrap class loader) is to be 1525 * used 1526 * 1527 * @param callerModule 1528 * The caller's module for which a new service loader is created 1529 * 1530 * @return A new service loader 1531 */ 1532 static <S> ServiceLoader<S> load(Class<S> service, 1533 ClassLoader loader, 1534 Module callerModule) 1535 { 1536 return new ServiceLoader<>(callerModule, service, loader); 1537 } 1538 1539 /** 1540 * Creates a new service loader for the given service. The service loader 1541 * uses the given class loader as the starting point to locate service 1542 * providers for the service. The service loader's {@link #iterator() 1543 * iterator} and {@link #stream() stream} locate providers in both named 1544 * and unnamed modules, as follows: 1545 * 1546 * <ul> 1547 * <li> <p> Step 1: Locate providers in named modules. </p> 1548 * 1549 * <p> Service providers are located in all named modules of the class 1550 * loader or to any class loader reachable via parent delegation. </p> 1551 * 1552 * <p> In addition, if the class loader is not the bootstrap or {@linkplain 1553 * ClassLoader#getPlatformClassLoader() platform class loader}, then service 1554 * providers may be located in the named modules of other class loaders. 1555 * Specifically, if the class loader, or any class loader reachable via 1556 * parent delegation, has a module in a {@linkplain ModuleLayer module 1557 * layer}, then service providers in all modules in the module layer are 1558 * located. </p> 1559 * 1560 * <p> For example, suppose there is a module layer where each module is 1561 * in its own class loader (see {@link ModuleLayer#defineModulesWithManyLoaders 1562 * defineModulesWithManyLoaders}). If this {@code ServiceLoader.load} method 1563 * is invoked to locate providers using any of the class loaders created for 1564 * the module layer, then it will locate all of the providers in the module 1565 * layer, irrespective of their defining class loader. </p> 1566 * 1567 * <p> Ordering: The service loader will first locate any service providers 1568 * in modules defined to the class loader, then its parent class loader, 1569 * its parent parent, and so on to the bootstrap class loader. If a class 1570 * loader has modules in a module layer then all providers in that module 1571 * layer are located (irrespective of their class loader) before the 1572 * providers in the parent class loader are located. The ordering of 1573 * modules in same class loader, or the ordering of modules in a module 1574 * layer, is not defined. </p> 1575 * 1576 * <p> If a module declares more than one provider then the providers 1577 * are located in the order that its module descriptor {@linkplain 1578 * java.lang.module.ModuleDescriptor.Provides#providers() lists the 1579 * providers}. Providers added dynamically by instrumentation agents (see 1580 * {@link java.lang.instrument.Instrumentation#redefineModule redefineModule}) 1581 * are always located after providers declared by the module. </p> </li> 1582 * 1583 * <li> <p> Step 2: Locate providers in unnamed modules. </p> 1584 * 1585 * <p> Service providers in unnamed modules are located if their class names 1586 * are listed in provider-configuration files located by the class loader's 1587 * {@link ClassLoader#getResources(String) getResources} method. </p> 1588 * 1589 * <p> The ordering is based on the order that the class loader's {@code 1590 * getResources} method finds the service configuration files and within 1591 * that, the order that the class names are listed in the file. </p> 1592 * 1593 * <p> In a provider-configuration file, any mention of a service provider 1594 * that is deployed in a named module is ignored. This is to avoid 1595 * duplicates that would otherwise arise when a named module has both a 1596 * <i>provides</i> directive and a provider-configuration file that mention 1597 * the same service provider. </p> 1598 * 1599 * <p> The provider class must be visible to the class loader. </p> </li> 1600 * 1601 * </ul> 1602 * 1603 * @apiNote If the class path of the class loader includes remote network 1604 * URLs then those URLs may be dereferenced in the process of searching for 1605 * provider-configuration files. 1606 * 1607 * <p> This activity is normal, although it may cause puzzling entries to be 1608 * created in web-server logs. If a web server is not configured correctly, 1609 * however, then this activity may cause the provider-loading algorithm to fail 1610 * spuriously. 1611 * 1612 * <p> A web server should return an HTTP 404 (Not Found) response when a 1613 * requested resource does not exist. Sometimes, however, web servers are 1614 * erroneously configured to return an HTTP 200 (OK) response along with a 1615 * helpful HTML error page in such cases. This will cause a {@link 1616 * ServiceConfigurationError} to be thrown when this class attempts to parse 1617 * the HTML page as a provider-configuration file. The best solution to this 1618 * problem is to fix the misconfigured web server to return the correct 1619 * response code (HTTP 404) along with the HTML error page. 1620 * 1621 * @param <S> the class of the service type 1622 * 1623 * @param service 1624 * The interface or abstract class representing the service 1625 * 1626 * @param loader 1627 * The class loader to be used to load provider-configuration files 1628 * and provider classes, or {@code null} if the system class 1629 * loader (or, failing that, the bootstrap class loader) is to be 1630 * used 1631 * 1632 * @return A new service loader 1633 * 1634 * @throws ServiceConfigurationError 1635 * if the service type is not accessible to the caller or the 1636 * caller is in an explicit module and its module descriptor does 1637 * not declare that it uses {@code service} 1638 * 1639 * @revised 9 1640 * @spec JPMS 1641 */ 1642 @CallerSensitive 1643 public static <S> ServiceLoader<S> load(Class<S> service, 1644 ClassLoader loader) 1645 { 1646 return new ServiceLoader<>(Reflection.getCallerClass(), service, loader); 1647 } 1648 1649 /** 1650 * Creates a new service loader for the given service type, using the 1651 * current thread's {@linkplain java.lang.Thread#getContextClassLoader 1652 * context class loader}. 1653 * 1654 * <p> An invocation of this convenience method of the form 1655 * <pre>{@code 1656 * ServiceLoader.load(service) 1657 * }</pre> 1658 * 1659 * is equivalent to 1660 * 1661 * <pre>{@code 1662 * ServiceLoader.load(service, Thread.currentThread().getContextClassLoader()) 1663 * }</pre> 1664 * 1665 * @apiNote Service loader objects obtained with this method should not be 1666 * cached VM-wide. For example, different applications in the same VM may 1667 * have different thread context class loaders. A lookup by one application 1668 * may locate a service provider that is only visible via its thread 1669 * context class loader and so is not suitable to be located by the other 1670 * application. Memory leaks can also arise. A thread local may be suited 1671 * to some applications. 1672 * 1673 * @param <S> the class of the service type 1674 * 1675 * @param service 1676 * The interface or abstract class representing the service 1677 * 1678 * @return A new service loader 1679 * 1680 * @throws ServiceConfigurationError 1681 * if the service type is not accessible to the caller or the 1682 * caller is in an explicit module and its module descriptor does 1683 * not declare that it uses {@code service} 1684 * 1685 * @revised 9 1686 * @spec JPMS 1687 */ 1688 @CallerSensitive 1689 public static <S> ServiceLoader<S> load(Class<S> service) { 1690 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 1691 return new ServiceLoader<>(Reflection.getCallerClass(), service, cl); 1692 } 1693 1694 /** 1695 * Creates a new service loader for the given service type, using the 1696 * {@linkplain ClassLoader#getPlatformClassLoader() platform class loader}. 1697 * 1698 * <p> This convenience method is equivalent to: </p> 1699 * 1700 * <pre>{@code 1701 * ServiceLoader.load(service, ClassLoader.getPlatformClassLoader()) 1702 * }</pre> 1703 * 1704 * <p> This method is intended for use when only installed providers are 1705 * desired. The resulting service will only find and load providers that 1706 * have been installed into the current Java virtual machine; providers on 1707 * the application's module path or class path will be ignored. 1708 * 1709 * @param <S> the class of the service type 1710 * 1711 * @param service 1712 * The interface or abstract class representing the service 1713 * 1714 * @return A new service loader 1715 * 1716 * @throws ServiceConfigurationError 1717 * if the service type is not accessible to the caller or the 1718 * caller is in an explicit module and its module descriptor does 1719 * not declare that it uses {@code service} 1720 * 1721 * @revised 9 1722 * @spec JPMS 1723 */ 1724 @CallerSensitive 1725 public static <S> ServiceLoader<S> loadInstalled(Class<S> service) { 1726 ClassLoader cl = ClassLoader.getPlatformClassLoader(); 1727 return new ServiceLoader<>(Reflection.getCallerClass(), service, cl); 1728 } 1729 1730 /** 1731 * Creates a new service loader for the given service type to load service 1732 * providers from modules in the given module layer and its ancestors. It 1733 * does not locate providers in unnamed modules. The ordering that the service 1734 * loader's {@link #iterator() iterator} and {@link #stream() stream} locate 1735 * providers and yield elements is as follows: 1736 * 1737 * <ul> 1738 * <li><p> Providers are located in a module layer before locating providers 1739 * in parent layers. Traversal of parent layers is depth-first with each 1740 * layer visited at most once. For example, suppose L0 is the boot layer, L1 1741 * and L2 are modules layers with L0 as their parent. Now suppose that L3 is 1742 * created with L1 and L2 as the parents (in that order). Using a service 1743 * loader to locate providers with L3 as the context will locate providers 1744 * in the following order: L3, L1, L0, L2. </p></li> 1745 * 1746 * <li><p> If a module declares more than one provider then the providers 1747 * are located in the order that its module descriptor 1748 * {@linkplain java.lang.module.ModuleDescriptor.Provides#providers() 1749 * lists the providers}. Providers added dynamically by instrumentation 1750 * agents are always located after providers declared by the module. </p></li> 1751 * 1752 * <li><p> The ordering of modules in a module layer is not defined. </p></li> 1753 * </ul> 1754 * 1755 * @apiNote Unlike the other load methods defined here, the service type 1756 * is the second parameter. The reason for this is to avoid source 1757 * compatibility issues for code that uses {@code load(S, null)}. 1758 * 1759 * @param <S> the class of the service type 1760 * 1761 * @param layer 1762 * The module layer 1763 * 1764 * @param service 1765 * The interface or abstract class representing the service 1766 * 1767 * @return A new service loader 1768 * 1769 * @throws ServiceConfigurationError 1770 * if the service type is not accessible to the caller or the 1771 * caller is in an explicit module and its module descriptor does 1772 * not declare that it uses {@code service} 1773 * 1774 * @since 9 1775 * @spec JPMS 1776 */ 1777 @CallerSensitive 1778 public static <S> ServiceLoader<S> load(ModuleLayer layer, Class<S> service) { 1779 return new ServiceLoader<>(Reflection.getCallerClass(), layer, service); 1780 } 1781 1782 /** 1783 * Load the first available service provider of this loader's service. This 1784 * convenience method is equivalent to invoking the {@link #iterator() 1785 * iterator()} method and obtaining the first element. It therefore 1786 * returns the first element from the provider cache if possible, it 1787 * otherwise attempts to load and instantiate the first provider. 1788 * 1789 * <p> The following example loads the first available service provider. If 1790 * no service providers are located then it uses a default implementation. 1791 * <pre>{@code 1792 * CodecFactory factory = ServiceLoader.load(CodecFactory.class) 1793 * .findFirst() 1794 * .orElse(DEFAULT_CODECSET_FACTORY); 1795 * }</pre> 1796 * @return The first service provider or empty {@code Optional} if no 1797 * service providers are located 1798 * 1799 * @throws ServiceConfigurationError 1800 * If a provider class cannot be loaded for any of the reasons 1801 * specified in the <a href="#errors">Errors</a> section above. 1802 * 1803 * @since 9 1804 * @spec JPMS 1805 */ 1806 public Optional<S> findFirst() { 1807 Iterator<S> iterator = iterator(); 1808 if (iterator.hasNext()) { 1809 return Optional.of(iterator.next()); 1810 } else { 1811 return Optional.empty(); 1812 } 1813 } 1814 1815 /** 1816 * Clear this loader's provider cache so that all providers will be 1817 * reloaded. 1818 * 1819 * <p> After invoking this method, subsequent invocations of the {@link 1820 * #iterator() iterator} or {@link #stream() stream} methods will lazily 1821 * locate providers (and instantiate in the case of {@code iterator}) 1822 * from scratch, just as is done by a newly-created service loader. 1823 * 1824 * <p> This method is intended for use in situations in which new service 1825 * providers can be installed into a running Java virtual machine. 1826 */ 1827 public void reload() { 1828 lookupIterator1 = null; 1829 instantiatedProviders.clear(); 1830 1831 lookupIterator2 = null; 1832 loadedProviders.clear(); 1833 loadedAllProviders = false; 1834 1835 // increment count to allow CME be thrown 1836 reloadCount++; 1837 } 1838 1839 /** 1840 * Returns a string describing this service. 1841 * 1842 * @return A descriptive string 1843 */ 1844 public String toString() { 1845 return "java.util.ServiceLoader[" + service.getName() + "]"; 1846 } 1847 1848 }