title: Implementing a cache using SoftReference
body: <p>I have a program that visualizes data sets. Several data sets can be loaded at a time (but only one data set can be displayed at a time), and the data sets can be large enough that memory becomes an issue. What I was thinking to do is to implement a caching mechanism so that the data sets are each cached in their own temporary file, and the GUI holds a soft reference to each data set so that memory is used more efficiently. This is what I approximately had in mind:</p>
  
  <pre><code>class DataSetReference extends SoftReference&lt;DataSet&gt; {
     private File cache;
  
     public DataSetReference(DataSet referent, byte[] rawData) {
        super(referent);
        // Skip error checking, etc.
        cache = File.createTempFile("abc", null);
        writeDataToCache(cache, rawData);
     }
  
     @Override
     public DataSet get() {
        if (super.get() == null) {
           refreshReferenceFromCache();
        }
        return super.get();
     }
  
     private refreshReferenceFromCache() {
        DataSet ds = parseDataSetFromFile(cache);
        // profit???
     }
  }
  </code></pre>
  
  <p>but then I realized that <code>SoftReference</code> is <strong>immutable</strong>, which kills that idea. It seems like what I have to do is to recreate the <code>DataSet</code> instance outside of the soft reference, then create a new soft reference and replace the old reference with the new in the GUI components that visualize the data sets.</p>
  
  <p>My question is: are there some patterns or examples for implementing caches with <code>SoftReference</code>? This is the first time I've attempted to use soft references, and I would feel more comfortable after looking at some other implementations. Thanks.</p>