title: Multiple Instances vs Cached Instances
body: <p>Consider an <code>interface</code> that has only one method:</p>
  
  <pre class="lang-java prettyprint-override"><code>Object getValue(String data);
  </code></pre>
  
  <p>Suppose this describes data transformation from a <code>String</code> to any other data type (assuming the transformation is valid). For data coming from a textual context, there may be several columns that are of the same data type and thus there would be multiple instances of the same data transformer.</p>
  
  <p>A long while ago I had written code to cache these instances instead of having multiple instances of the same object:</p>
  
  <pre class="lang-java prettyprint-override"><code>private HashMap&lt;Class&lt;? extends T&gt;, T&gt; map;
  
  public synchronized T getInstance(Class&lt;? extends T&gt; type) throws IllegalArgumentException
  {
    T instance = map.get(type);
    if (instance == null)
    {
      try
      {
        instance = type.newInstance();
      }
      catch (Exception ex)
      {
        throw new IllegalArgumentException("The provided class cannot be instantiated: "
                + type.getName() + "\n" + ex);
      }
      map.put(type, instance);
    }
    return instance;
  }
  </code></pre>
  
  <p>Since these classes have no state, it seemed a waste, at the time to have many instances of the same class when a single shared instance would do.</p>
  
  <p>However, it is likely more overhead to maintain the mapping than to have multiple instances of the same object (even though a single instance could be shared). I mean, even though there are multiple instances, the method code is only placed in memory once right? So in my mind, the JVM is effectively keeping a cache for me.</p>
  
  <p>Any thoughts on the matter? Could the singleton instance-cache approach be better?</p>
  
  <p>Thank you for reading my post.</p>