Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ConcurrentHashMap atomic get if present

How do you perform a safe get if present operation on a Concurrent Hash Map? (same thing like putIfAbsent)

Bad example, not very thread safe (check then act situation):

ConcurrentMap<String, SomeObject> 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;
}

Another bad example would be:

   public boolean setOption(String id, Object option){
       if (concMap.contains(id)){
           concMap.get(id).setOption(option);
           return true;
       }
       return false;
    }

The desirable thing here is to not bottleneck the add, remove and get operations by synchronizing them.

Thanks

like image 512
cdmihai Avatar asked Dec 28 '22 04:12

cdmihai


1 Answers

The get() method on a ConcurrentHashMap is atomic. Since that map does not allow null values, get() implements "get if present": If the result is null, the key was not present.

like image 138
Christian Semrau Avatar answered Jan 08 '23 16:01

Christian Semrau