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

Brian Goetz brian@quiotix.com
Thu, 23 Dec 2004 12:19:53 -0500

No.  There is no way to lock a CHM for exclusive access.  However, you 
might be able to bootstrap the functionality you want using the atomic 
putIfAbsent and Future, depending on your requirements.

Map<K, Future<V>> myMap = new ConcurrenHashMap<K, Future<V>>();
FutureTask t = new FutureTask(runnable which calculates value);
if (myMap.putIfAbsent(k, t)) {

And, if you want to retrieve the value associated with key k, do

> 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
> ConcurrentHashMap?
> Thanks,
> Donnie
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest@altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest