Multiple Providers and Provider Selection
You'll learn how to handle situations where multiple modules provide implementations of the same service interface and how consumers can iterate through or choose specific providers.
The Power of Multiple Implementations
In the real world, you often have competing implementations of the same service. Think of it like a plugin system: multiple modules can each offer their own version of a text formatter, logger, or database driver. The Java Module System's service mechanism fully supports this scenario—multiple modules can use provides...with for the same service interface.
How ServiceLoader Handles Multiple Providers
When you call ServiceLoader.load(MyService.class), the ServiceLoader doesn't just return one implementation—it returns all available providers from modules that declare provides MyService with MyServiceImpl. The ServiceLoader lazily discovers them as you iterate.
You have two main approaches:
1. Iterate through all providers:
ServiceLoader<TextFormatter> loader = ServiceLoader.load(TextFormatter.class);
for (TextFormatter formatter : loader) {
System.out.println("Found: " + formatter.getClass().getName());
// Use formatter...
}
2. Use stream API for filtering/selection:
ServiceLoader<TextFormatter> loader = ServiceLoader.load(TextFormatter.class);
Optional<TextFormatter> preferred = loader.stream()
.map(ServiceLoader.Provider::get)
.filter(f -> f.getClass().getName().contains("Json"))
.findFirst();
Selection Strategies
Since multiple providers coexist, your consumer module must decide how to select among them. Common strategies include:
- Use the first available provider
- Filter by implementation class name or properties
- Try each provider until one succeeds
- Use all providers (aggregating results)
Key Takeaway: Multiple modules can provide implementations of the same service interface; consumers use ServiceLoader's iteration or stream methods to discover and select the appropriate provider(s) at runtime.