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