[concurrency-interest] CHM#replace(key, null, newValue)

Bob Lee crazybob at crazybob.org
Tue Apr 1 10:19:48 EDT 2008


It's part of an interface (ConcurrentMap). You can't really break
backward compatibility.

You could write a static utility method:

  /** Repeatedly calls replace or putIfAbsent... */
  static <K, V> void replaceOrPut(ConcurrentMap<K, V> m, K key, V
oldValue, V newValue) { ... }

Bob

On Tue, Apr 1, 2008 at 3:18 AM, Matthias Ernst <matthias at mernst.org> wrote:
> [Never went to the list due to wrong sender address]
>
>  On Sat, Jan 12, 2008 at 11:15 AM, Matthias Ernst
>  <ernst.matthias at gmail.com> wrote:
>  > Hi,
>  >
>  >  I found myself writing a loop to atomically update a ConcurrentHashMap
>  >  like this:
>  >
>  >  ConcurrentHashmap<K, V> map = ...;
>  >  K key = ...;
>  >
>  >  V oldValue, newValue;
>  >  while(!map.replace(key, oldValue=map.get(key), newValue=add(oldValue, delta)));
>  >
>  >  Unfortunately it doesn't work, if the key is not present in the map yet.
>  >  Instead, I have to do something like:
>  >
>  >  success =
>  >    (oldValue==null) ?
>  >      (null==chm.putIfAbsent(key, newValue)) :
>  >      chm.replace(key, oldValue, newValue).
>  >
>  >
>  >  I think it would be both intuitive and reduce cruft, if #replace could
>  >  call #putIfAbsent itself.
>  >  What do you think? Wouldn't this come up in every piece of code that
>  >  uses replace and an unknown set of keys?
>  >
>  >  Matthias
>  >
>  _______________________________________________
>  Concurrency-interest mailing list
>  Concurrency-interest at altair.cs.oswego.edu
>  http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>


More information about the Concurrency-interest mailing list