Synchronize write to two collections
        Posted  
        
            by 
                glaz666
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by glaz666
        
        
        
        Published on 2012-10-08T21:28:48Z
        Indexed on 
            2012/10/08
            21:37 UTC
        
        
        Read the original article
        Hit count: 251
        
I need to put some value to maps if it is not there yet. The key->value (if set) should always be in two collections (that is put should happen in two maps atomically). I have tried to implement this as follows:
private final ConcurrentMap<String, Object> map1 = new ConcurrentHashMap<String, Object>();
private final ConcurrentMap<String, Object> map2 = new ConcurrentHashMap<String, Object>();
public Object putIfAbsent(String key) {
    Object retval = map1.get(key);
    if (retval == null) {
        synchronized (map1) {
            retval = map1.get(key);
            if (retval == null) {
                Object value = new Object(); //or get it somewhere
                synchronized (map2) {
                    map1.put(key, value);
                    map2.put(key, new Object());
                }
                retval = value;
            }
        }
    }
    return retval;
}
public void doSomething(String key) {
    Object obj1 = map1.get(key);
    Object obj2 = map2.get(key);
    //do smth
}
Will that work fine in all cases? Thanks
© Stack Overflow or respective owner