I recently ran into the situation where I wanted to do lazy, on-demand, initialization of a registry. In previous applications, I would just use get()/put() from java.util.ConcurrentHashMap because I didn’t care if something was created more than once accidentally as it would eventually, and quickly, sort itself out and all I’d lose is a tiny garbage collection. Unfortunately, in my current project, a registry entry cannot be allocated twice as two different versions of it might be used concurrently and each registry entry holds and maintains state. These resources need to be individually unique. Thankfully, java.util.ConcurrentHashMap has a nice method called putIfAbsent(). This method does the atomic equivalent of:

if (!map.containsKey(key)) {
   return map.put(key, value);
} else {
   return map.get(key);
}

So, what I can do is do a mini double check. When I lookup at entry, if it doesn’t exist, allocate a temporty version of it and call putIfAbsent.

public V get(K key) {
   V value = concurrentMap.get(key);
   if (value != null) return value;

   value = new Value(...);
   V tmp = concurrentMap.putIfAbsent(value);
   if (tmp == null) {
      return value;
   } else {
      value.cleanup();
      return tmp;
   }
}

If putIfAbsent returns null, then I know nobody has created a version concurrently.  If it doesn’t return null, then I know somebody has initialized this entry concurrently.  In that case, I cleanup the created value, and return the one already in the registry.  This looks a lot like the double-check-nono, but it actually isn’t as ConcurrentHashMap performs the putIfAbsent atomically.