title: Java Services SPI and Memory Leaks
body: <p>I have 100s of services which I am currenly revamping/cleaning up so that they implementation complexity can be abstracted out. However, what I have noticed is that java SPI doesn't provision singleton-based SPI setup. Instead, it provides guideline for how to achieve this when SPI-based services are handled.</p>
  
  <p><a href="https://docs.oracle.com/javase/tutorial/ext/basics/spi.html#singleton" rel="nofollow noreferrer">https://docs.oracle.com/javase/tutorial/ext/basics/spi.html#singleton</a></p>
  
  <p>the following code</p>
  
  <p><code>ServiceProvider sp = ServiceLoader.load(ProvierAPI.class).iterator().next()</code></p>
  
  <p>loads a new instance of <code>ServiceProvider</code> every time the <code>ServiceLoader</code> is queried. But I am not quite sure how it's <strong><em>not</em></strong> a memory safe operation since the following code will ensure a Garbage collection occurs after the context leaves the stack frame?</p>
  
  <pre><code>    public void doFoo() {
  
       ServiceProvider sp = ServiceLoader.load(ProvierAPI.class).iterator().next();
  
       sp.doServiceFoo();
  
       doSomethingElse();
  
       return;
  }
  </code></pre>
  
  <p>Does using singletons "Truly" serve any benefit here? From what I understand, Singleton technically means a lot of permanent object references in memory (so called static <code>getInstance()</code> ). </p>
  
  <p>Is it still better to use Singleton's for SPI related implementations?</p>