title: Create and put a map value only if not already present, and get it: thread-safe implementation
body: <p>What is the best way to make this snippet thread-safe?</p>
  
  <pre class="lang-java prettyprint-override"><code>private static final Map&lt;A, B&gt; MAP = new HashMap&lt;A, B&gt;();
  
  public static B putIfNeededAndGet(A key) {
      B value = MAP.get(key);
      if (value == null) {
          value = buildB(...);
          MAP.put(key, value);
      }
      return value;
  }
  
  private static B buildB(...) {
      // business, can be quite long
  }
  </code></pre>
  
  <p>Here are the few solutions I could think about:</p>
  
  <ol>
  <li>I could use a <code>ConcurrentHashMap</code>, but if I well understood, it <em>just</em> makes the atomic <code>put</code> and <code>get</code> operations thread-safe, i.e. it does not ensure the <code>buildB()</code> method to be called only once for a given value.</li>
  <li>I could use <code>Collections.synchronizedMap(new HashMap&lt;A, B&gt;())</code>, but I would have the same issue as the first point.</li>
  <li>I could set the whole <code>putIfNeededAndGet()</code> method <code>synchronized</code>, but I can have really many threads accessing this method together, so it could be quite expensive.</li>
  <li>I could use the double-checked locking pattern, but there is still the related <a href="https://stackoverflow.com/a/11195509/1225328">out-of-order writes issue</a>.</li>
  </ol>
  
  <p>What other solutions may I have?</p>
  
  <p>I know this is a quite common topic on the Web, but I didn't find a clear, full and working example yet.</p>