[concurrency-interest] Questions on ConcurrentHashMap

Gregg Wonderly gregg at cytetech.com
Wed Nov 28 12:46:02 EST 2007


Grace Kwok wrote:
> I am trying to think of the most concurrent and correct way of
> implementing this.

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

But I am not clear on exactly when you fill the map.  If you fill the map on a 
"get", then you may instead choose to use a future to cause those doing a get to 
wait for the map to "appear" in a filled state.

public void clear() {
	map = null;
}

volatile Future<ConcurrentHashMap<T,K>> mapFuture;

public T get( K key ) {
	if( map == null ) {
		if( mapFuture == null ) {
			synchronized( mapLock ) {
				if( mapFuture == null )
					mapFuture = startMapBuild();
			}
		}
		map = mapFuture.get();
	}
	return map.get( key );
}

This focuses the locking into the moment that is needed while allow the 
concurrency in ConcurrentHashMap to be exploited on gets().

Gregg Wonderly


More information about the Concurrency-interest mailing list