title: Atomically incrementing counters stored in ConcurrentHashMap
body: <p>I would like to collect some metrics from various places in a web app. To keep it simple, all these will be counters and therefore the only modifier operation is to increment them by 1. </p>
  
  <p>The increments will be concurrent and often. The reads (dumping the stats) is a rare operation.</p>
  
  <p>I was thinking to use a <em>ConcurrentHashMap</em>. The issue is how to <em>increment</em> the counters correctly. Since the map doesn't have an "increment" operation, I need to read the current value first, increment it than put the new value in the map. Without more code, this is not an atomic operation.</p>
  
  <p>Is it possible to achieve this without synchronization (which would defeat the purpose of the <em>ConcurrentHashMap</em>)? Do I need to look at <a href="https://github.com/google/guava" rel="noreferrer">Guava</a> ?</p>
  
  <p>Thanks for any pointers. </p>
  
  <hr>
  
  <p><strong>P.S.</strong><br>
  There is a related question on SO (<a href="https://stackoverflow.com/questions/81346/most-efficient-way-to-increment-a-map-value-in-java">Most efficient way to increment a Map value in Java</a>) but focused on performance and not multi-threading</p>
  
  <p><strong>UPDATE</strong><br>
  For those arriving here through searches on the same topic: besides the answers below, there's a useful <a href="http://www.slideshare.net/sjlee0/robust-and-scalable-concurrent-programming-lesson-from-the-trenches" rel="noreferrer">presentation</a> which incidentally covers the same topic. See slides 24-33. </p>