title: Fastest way to initialize a value for ConcurrentHashMap
body: <p>ConcurrentHashMap is often used in concurrent environments for aggregation of some events under a key - like counting hits for some string values. In case we don't know the keys in advance we need to have a good way to initialize key on need, it should to be fast and safe in terms of concurrency.
  What is the best pattern (in terms of efficiency) for this problem?</p>
  
  <p>I will use a model map with <code>&lt;String, AtomicInteger&gt;</code> declared like:</p>
  
  <pre><code>ConcurrentHashMap&lt;String, AtomicInteger&gt; map = new ConcurrentHashMap&lt;&gt;();
  </code></pre>
  
  <p>But it could be a map with any key-value pair, where we need to initialize a key-value pair if the key does not already exists in the map and mutate the state of value to record event.</p>
  
  <p>There are two popular approaches:
  The first one uses <code>ConcurrentHashMap.putIfAbsent</code>:</p>
  
  <pre><code>AtomicInteger count = map.get(s);
  if (count == null) {
      count = new AtomicInteger(0);
      AtomicInteger prevCount = map.putIfAbsent(s, count);
      if (prevCount != null) {
          count = prevCount;
      }
  }
  count.incrementAndGet();
  </code></pre>
  
  <p>The second one uses <code>ConcurrentHashMap.computeIfAbsent</code>:</p>
  
  <pre><code>AtomicInteger count = map.computeIfAbsent(s, (k) -&gt; new AtomicInteger(0));
  count.incrementAndGet();
  </code></pre>
  
  <p>Which one is better suited for this task? Are there other approaches?</p>