title: Java ConcurrentHashMap atomic get if present
body: <p>How do you perform a safe get if present operation on a Concurrent Hash Map? (same thing like putIfAbsent)</p>
  
  <p>Bad example, not very thread safe (check then act situation):</p>
  
  <pre><code>ConcurrentMap&lt;String, SomeObject&gt; concMap = new ...
  
  //... many putIfAbsent and remove operations
  
  public boolean setOption(String id, Object option){
     SomeObject obj = concMap.get(id);
  
     if (obj != null){
        //what if this key has been removed from the map?
        obj.setOption(option);
        return true;
     }
  
     // in the meantime a putIfAbsent may have been called on the map and then this
     //setOption call is no longer correct
  
     return false;
  }
  </code></pre>
  
  <p>Another bad example would be:</p>
  
  <pre><code>   public boolean setOption(String id, Object option){
         if (concMap.contains(id)){
             concMap.get(id).setOption(option);
             return true;
         }
         return false;
      }
  </code></pre>
  
  <p>The desirable thing here is to not bottleneck the add, remove and get operations by synchronizing them.</p>
  
  <p>Thanks</p>