The java.util.ServiceLoader Class
What you'll learn: How ServiceLoader automatically discovers and loads service implementations from the module path at runtime without hard-coded dependencies.
What Is ServiceLoader?
ServiceLoader is Java's built-in mechanism for implementing the Service Provider Interface (SPI) pattern. It acts as a discovery engine that finds and instantiates service implementations dynamically, without your code needing to know the exact implementation classes at compile time.
Think of it like a restaurant finder app: you specify what you want (Italian food), and it discovers who provides it (specific restaurants), even if new ones open after your app was built.
How ServiceLoader Works
At runtime, ServiceLoader scans the module path looking for:
- Service declarations in
module-info.javafiles (viaprovidesandusesdirectives) - Provider configuration files (legacy classpath mechanism, pre-JPMS)
It then instantiates implementations via their no-arg constructors and hands them to you as an Iterable.
Basic usage pattern:
ServiceLoader<MyService> loader = ServiceLoader.load(MyService.class);
for (MyService service : loader) {
service.doWork(); // Calls the actual implementation
}
Key Features
- Lazy loading: Implementations are instantiated only when you iterate
- Module-aware: Respects JPMS visibility and
providesdeclarations - Decoupling: Consumer modules don't need compile-time dependencies on providers
- Extensibility: New providers can be added without changing consumer code
Discovery Process
ServiceLoader.load() searches through readable modules on the module path, looking for those that declare provides MyService with SomeImplementation, then instantiates SomeImplementation using reflection (via the no-arg constructor).
Key Takeaway: ServiceLoader enables runtime discovery and instantiation of service implementations from the module path, allowing true plugin-style extensibility without compile-time coupling.