[concurrency-interest] Can this be done with ConcurrentHashMap ?

David Holmes dholmes@dltech.com.au
Fri, 24 Dec 2004 10:44:36 +1000

> Donnie Hale writes:
> 2) I'll admit to being a little disappointed. A host of wonderful new
> concurrency utilities have been released, and, the first time I go to use
> them, I come up against this.

When you use ConcurrentHashMap you get high-throughput concurrent access
with no locking. The downside is that you cannot get exclusive use of the
map by any simple means, to do a lengthy atomic operation. You can't have
both high-throughput concurrent access and arbitrary atomic actions. So the
choice is yours: go for ConcurrentHashMap and do atomic stuff the harder
way; or go with a synchronizedHashMap and lose the throughput.

Your original problem can also be solved by locking something other than the
hashmap - depending on how different keys may be generated. For example:

Object myvalue = mymap.get(mykey);
if (myvalue == null) {
  synchronized(keyGenerationLock) {
     myvalue = mymap.get(mykey);
     if (myvalue = null) {
       // lengthy operation to generate myvalue
       mymap.put(mykey, myvalue);

This solution only blocks the threads actually interested in the same key,
and doesn't lock the entire map at any stage.

David Holmes