title: How can I perform a thread-safe get then remove with ConcurrentHashMap?
body: <p>In an interview, I was asked to check whether following code works as intended.</p>
  
  <pre><code>ConcurrentHashMap&lt;Integer, Integer&gt; chm = new ConcurrentHashMap&lt;&gt;();
  
  if (chm.get(key) != null) {
      chm.get(key).doSomething();
      chm.remove(key);
  }
  </code></pre>
  
  <p>According to JavaDocs, <code>get</code> returns value of last completed update operation. So if thread 1 already called <code>chm.remove(key)</code> and if thread 2 came inside the if statement and is about to call <code>get</code> method then we might get an exception. Is this correct?</p>
  
  <p>How can I make this thread-safe?</p>