[concurrency-interest] MappingFunction for ConcrrentMap.replace()

Alex Lam S.L. alexlamsl at gmail.com
Sun Jul 15 07:04:06 EDT 2012


After encountering the need for CSKLM.computeIfAbsent(), I now run
into a case where I would like a variation of replace(K,V,V) which
does:

replace(key, expected, mappingFunction)

In my particular use-case I am currently doing this:

ConcurrentMap<K, Reference<V>> map;

V get(K key) {
  Reference<V> ref = map.get(key);
  V value = ref == null ? null : ref.get();
  while (value == null) {
    value = createValue(key);
    ref = map.replace(key, ref, wrap(value));
    if (ref != null)
      value = ref.get();
  }
  return value;
}



Alex.


More information about the Concurrency-interest mailing list