Course contentsShow
← Java
Lesson 2499 of 2,87047. Java Platform Module System (JPMS)Free lesson

The java.util.ServiceLoader Class

Learning how ServiceLoader discovers and instantiates service implementations at runtime from the module path.

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:

  1. Service declarations in module-info.java files (via provides and uses directives)
  2. 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 provides declarations
  • 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.