Q:

ConcurrentHashMap#putIfAbsent but remove item if present

I've got a java.util.concurrent.ConcurrentHashMap, and I want to put something if it's not present, but if something is present, I'd like to also remove it. Something like:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
// ...
V value = map.putIfAbsent(k, new V(/* ... */));
if (value != null) {
  map.remove(k);
}

Except of course I'd like it to be thread-safe.
Is there a clean way to do this? Or should I just use a HashMap and synchronize access?
My understanding is that update operations are synchronized anyway, and I don't expect significant lock contention, so adding more synchronization isn't a big deal.

A:

If performance is not an issue, you can use the decorator design pattern with ConcurrentHashMap and add synchronization as follows:
public class MyMap<K, V> {

    private ConcurrentHashMap<K, V> map;

    public V put(K key, V value) {
        synchronize(map) {
            if(map.get(key) != null) {
                map.remove(key);
            } else {
                map.put(key, value);
        }
    }

    public V get(Object key) {
        synchronize(map) {
            return map.get(key);
        }
    }
}

If performance is an issue, you can implement an optimized implementation similar to the one implemented in the ConcurrentHashMap. for that, I suggest you take a look at the ConcurrentHashMap source code.

