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

Larry Riedel larryr@saturn.sdsu.edu
23 Dec 2004 19:53:57 -0000


> 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.

I would be inclined to use a sentinel value (distinguished
invalid value) for each entry whose valid value is not ready
yet, and provide a wrapper which hides entries whose value is
the sentinel, and has "prepare(key)" and "commit(key,value)"
methods exposed to those classes whose methods generate values,
so those classes can can "prepare" an entry for a key, and if
that succeeds, generate the valid value and "commit" it.

Classes/methods not involved in the two phase generation of
entries would only be given plain "ConcurrentMap" references to
the wrapper, and would not be aware of the existence of entries
whose values are not ready yet... as long as they do not try to
put an entry whose key already has a corresponding "prepare"d
but not "commit"ted entry; if such a situation could occur for
that application, maybe that class/method should have been using
the "prepare" and "commit" approach in the first place.


Larry