does java.util.ServiceLoader load only a single instance of a service

2k Views Asked by At

I want to ask whether the ServiceLoader.load() can help me create multiple instances of the loaded service?

I have been doing some testing and its seems it can only load one instance of the service at a time. If it is possible to have multiple instances, can someone explain how I can achieve this?

1

There are 1 best solutions below

4
On BEST ANSWER

You don't want to use the ServiceLoader itself to create multiple copies. You could, using the reload method of the loader, but that is not the intended usage of it, probably doesn't perform very well, and also has the side effect that other implementations are reloaded as well.

More likely, what you want to do is instead of create a factory class (or some similar concept), which itself creates the instances of the class you actually want to use, in the end, and use the service loader to load such factory instances instead.