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

Matthias Ernst matthias at mernst.org
Tue Apr 1 06:18:56 EDT 2008


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


More information about the Concurrency-interest mailing list