title: Properly setting up a simple server-side cache
body: <p>I'm trying to set up a server-side cache properly and I'm looking for constructive criticism on the setup I have currently.  The cache is loaded when the Servlet starts and never changed again, so in effect it's a read-only cache.  It obviously needs to stay in memory for the lifetime of the Servlet.  Here's how I have it set-up </p>
  
  <pre><code>private static List&lt;ProductData&gt; _cache;
  private static ProductManager productManager;
  
  private ProductManager() {
      try {
          lookup();
      } catch (Exception ex) {
          _cache = null;
      }
  }
  
  public synchronized static ProductManager getInstance() {
      if (productManager== null) {
          productManager= new ProductManager();
      }
      return productManager;
  }
  </code></pre>
  
  <p>The cache is setup by the Servlet as below:</p>
  
  <pre><code>private ProductManager productManager;
  
  public void init(ServletConfig config) throws ServletException {
      productManager = ProductManager.getInstance();
  }
  </code></pre>
  
  <p>And finally, this is how I access it:</p>
  
  <pre><code>public static ProductData lookup(long id) throws Exception {
      if (_cache != null) {
          for (int i = 0; i &lt; _cache.size(); i++) {
              if (_cache.get(i).id == id) {
                  return _cache.get(i);
              }
          }
      }
  
      // Look it up in the DB.
  }
  
  public static List&lt;ProductData&gt; lookup() throws Exception {
      if (_cache != null) {
          return _cache;
      }
  
      // Read it from the DB.
  
      _cache = list;
      return list;
  }
  </code></pre>