[concurrency-interest] Questions on ConcurrentHashMap

Grace Kwok gykwok at gmail.com
Wed Nov 28 01:17:21 EST 2007


Hi,

I am considering replacing my synchronized HashMap cache to be a
ConcurrentHashMap.

1) Consider these operations on a populated map:
- map.clear() is called
- immediately or concurrently afterwards map.get(A) and map.get(B) are called.

We know for sure that if map is a synchronized HashMap, the result of
A and B would be null.

However, if map is a concurrentHashMap, the results of get(A) and
get(B) could be any of the followings [AResult, BResult], [null,
null], [AResult, null], [null, BResult].  Am I correct?

If so, is there a way around it such that this old behavior remains
and I can still take advantage of the concurrency in
ConcurrentHashMap?

2) I have a map cache that behaves as such:
i) Everytime a request is invoked to get a value corresponding to a
certain key, the whole map will be populated if it has not been done.
After which, the map would not change and there would continue to be
concurrent gets accessing it.
ii) When the map needs to be invalidated, the whole map would be invalidated.
iii) After which, we go back to the first step i).

I am trying to think of the most concurrent and correct way of
implementing this.

Below is psuedo code that I thought of:

static volatile FutureTask<K, V> task = new FutureTask<K, V>(new
Callable(){...});  where call() method would populate and return a non
modifiable map.

private Map<K, V> getMyCache()
{
   return task.get();
}

public V getValue(K key)
{
     getMyCache().get(key);
}

public void invalidate()
{
    task = new FutureTask<K, V>(new Callable(){...});
}

Please comment on the idea as well as suggestion of a better way of doing this.

Thank you very much!

Grace


More information about the Concurrency-interest mailing list