[concurrency-interest] Questions on ConcurrentHashMap

David Holmes dcholmes at optusnet.com.au
Wed Nov 28 02:32:12 EST 2007


Grace,

Looking at Q#2

> 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();
> }

This won't cause task.run() to execute. Though you could create a custom
FutureTask that provides that functionality - ie first getter runs, and uses
internal synchronization.

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

This doesn't invalidate the map for callers of getValue() that have already
retrieved the old map from getMyCache() but have not yet executed get(key)
on it.

If you need these actions to be atomic then I think you will not be able to
benefit from using ConcurrentHashMap, as you will need external locking
anyway.

Cheers,
David Holmes



More information about the Concurrency-interest mailing list