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

Donnie Hale donnie@haleonline.net
Thu, 23 Dec 2004 11:12:05 -0500

I've searched the list history (I have most all of it locally :) and read
the API docs, but I'm not sure if ConcurrentHashMap directly supports this
or not. I want to check if a key is present in the map and, if not, proceed
to perform a lengthy operation to generate the value for the key then put it
in the map. However, I don't want another thread coming along and, not
finding that same key in the map, starting the same lengthy operation to
generate the value.

Something like:

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

With past JDK capabilities, I'd synchronize on mymap for the duration of
that operation. With certain flavors of ReadWrite locks, I'd get a readlock
before the whole operation and promote to writelock if I had to do the
lengthy operation and put.

Assuming what I want to do is clear, is this possible with a