[concurrency-interest] Questions on ConcurrentHashMap

Joe Bowbeer joe.bowbeer at gmail.com
Wed Nov 28 16:29:19 EST 2007


On Nov 28, 2007 9:46 AM, Gregg Wonderly wrote:
>
> When I have all or nothing situations like this, I will often rebuild the map
> into a local referenced instance, and then overwrite the global reference with
> the new instance to create an "atomic" swap to the new values without having to
> "wait" for them everywhere else.
>
> Based on what I think you are doing on clear, it might look something like the
> following.
>
> volatile ConcurrentHashMap<T,K> map = ...
>
> public void clear() {
>         ConcurrentHashMap<T,K> newmap = ...
>         fillmap( newmap );
>         map = newmap;
> }
>

Is there also a requirement that get(A) and get(B) return values from
the same version of the cache?

If so, you can stash the map reference before fetching the values:

  Map<K,V> cache = map;
  cachedA = cache.get(A);
  cachedB = cache.get(B);

Or fetch the values optimistically and then retry if you detect an update:

  Map<K,V> prev = map;
  do {
    cachedA = map.get(A);
    cachedB = map.get(B);
  } while (map != prev);

--
Joe Bowbeer


More information about the Concurrency-interest mailing list