CKTIS / Java
util.ServiceLoader: practical reference
util.ServiceLoader: practical reference: ServiceLoader<S> locates zero, one, or many service providers in the runtime environment and loads them lazily without exposing implementation locations.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.ServiceLoaderServiceLoader locates zero, one, or many service providers in the runtime environment and loads them lazily without exposing implementation locations.
Use it as an extension point: a consumer module declares uses, a provider declares provides, and stream can inspect Provider.type before instantiation.
ServiceLoader is not thread-safe, and bad configuration or provider construction may raise ServiceConfigurationError only during iteration.
Located instances are cached; reload clears the cache and invalidates existing iterators and streams, which can then throw ConcurrentModificationException.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var providers = java.util.ServiceLoader.load(java.nio.file.spi.FileSystemProvider.class);
System.out.println(providers.findFirst().isPresent());
}
}
Result
true
The example exercises the documented element in a small deterministic program and compares exact standard output.