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

Doug Lea dl@cs.oswego.edu
Thu, 23 Dec 2004 11:50:40 -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.

Usually, The best way to get the effect you want here is to create a
cheap proxy class for your value objects, that only computes them
on-demand. Then you can do a quick put of the proxy, and force the
first caller to compute the value.  This is a variant of a Future.  If
you like, you could structure your proxy as a Future.

The reason for not supporting this directly in any ConcurrentMap
method is that implementations can't and/or shouldn't maintain
atomicity across a lengthy callback, or deal with possible exceptions
it might throw.