title: Synchronization in a HashMap cache
body: <p>I've got a web application where people ask for resources. This resources are cached using a synchronized hash map for efficiency. The problem here is when two different requests come for the same uncached resource at the same time: the operation retrieving the resources takes up a lot of memory, so I want to avoid calling it more than once for the same resource.</p>
  
  <p>Can somebody please tell me if there is any potential problem with the following snippet? Thanks in advance.</p>
  
  <pre><code>private Map&lt;String, Resource&gt; resources = Collections.synchronizedMap(new HashMap&lt;String, Resource&gt;());
  
  public void request(String name) {
  
    Resource resource = resources.get(name);
  
    if (resource == null) {
      synchronized(this) {
        if (resources.get(name) == null) {
          resource = veryCostlyOperation(name); // This should only be invoked once per resource...
          resources.put(resource);
        } else {
          resource = resources.get(name);
        }
      }
    }
  
    ...
  
  }
  </code></pre>