3

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?

CJ Ramki
  • 2,620
  • 3
  • 25
  • 47
MykelXIII
  • 1,085
  • 1
  • 8
  • 16
  • The question is not entirely clear. Please elaborate on what it is you want to achieve by loading multiple instances. Are you talking about multiple implementations of a particular service, or do you merely want to create multiple "copies" of a certain service for other reasons? – Dolda2000 Jan 29 '14 at 05:19
  • Thank you for your reply. What i mean is I simply want to create multiple copies of a certain service – MykelXIII Jan 29 '14 at 05:21

1 Answers1

4

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.

Dolda2000
  • 25,216
  • 4
  • 51
  • 92
  • Thank you. I had the same thoughts. I am new to plug in development in java and I am unsure how dependencies should be injected. Is it a clean way to inject dependencies using the factory class? Or does java have a framework to inject dependencies similar to how the MEF of C# works. – MykelXIII Jan 29 '14 at 05:28
  • You'll have to elaborate on exactly what you mean by "injecting dependencies", because that is not a term that maps directly to any Java concept. I don't know what MEF is, and I haven't used C#. If you're simply talking about making libraries available to your program, the "normal" way to do that is simply to add them to the JVM's classpath on startup, though various frameworks may have other preferred ways of doing it. – Dolda2000 Jan 29 '14 at 05:33
  • What I mean is for example i have class A that has a parameter class B in its constructor. This results in class A having a dependency on class B. I wanna ask a clean way to handle this with out having to create a new instance of B myself. If creating a new instance of B in the factory is the only way then it is ok with me. Sorry I am still not good at explaining. – MykelXIII Jan 29 '14 at 05:43
  • That seems like a broader question, so if you want more information on it, you should probably open a new question on that subject rather than handling it here in comments. – Dolda2000 Jan 29 '14 at 05:50