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

Matthias Ernst matthias at mernst.org
Tue Apr 1 10:45:35 EDT 2008


On Tue, Apr 1, 2008 at 4:19 PM, Bob Lee <crazybob at crazybob.org> wrote:
> It's part of an interface (ConcurrentMap). You can't really break
>  backward compatibility.

I guess you're right. I was just wondering whether that interface was
specified in an unfortunate manner or whether I'm missing something.
That if-statement is boilerplate everyone trying to update a CHM will
have to write.

>
>  You could write a static utility method:

in commons-helpers?

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

Rather boolean replaceOrPut(ConcurrentMap<K, V> m, K key, V oldValue,
V newValue) { ... }

The full monty would require a closure:
>   static <K, V> void replaceOrPut(ConcurrentMap<K, V> m, K key, {V=>V} updateFunction)


Matthias


>
>  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