[concurrency-interest] CHM putIfAbsent

Ben Manes ben_manes at yahoo.com
Wed May 26 04:03:57 EDT 2010

The memoization idiom can be easily implemented with futures, as described in JCiP. A mature implementation is provided in Google's MapMaker and Ehcache's SelfPopulatingCache, among others.  Below shows a simple example of rolling this by hand to give you an idea of how this trick can be done and can be easily extended to perform bulk memoization. It will not be performed under the CHM's segment lock, which would provide slightly different semantics by restricting further segment write operations.

FutureTask<V> task = new FutureTask<V>(
              new Callable<V>() {
                    public V call() throws Exception {
                          // compute and return
          Future<V> future = map.putIfAbsent(key, task);
          if (future == null) {
                future = task;
          try {
                return future.get();
          } catch (Exception e) {
                map.remove(key, future);
                throw e;


From: Nabib El-Rahman <nabiber at gmail.com>
To: concurrency-interest at cs.oswego.edu
Sent: Wed, May 26, 2010 12:37:03 AM
Subject: [concurrency-interest] CHM putIfAbsent


I don't know if this exist, But I need someway of executing an set of statements atomically under the lock of the appropriate CHM segment.
That way I keep the correctness of the synchronization while still getting the concurrency benefit of CHM.

Something like this:

 public V putIfAbsent(K key, Callable callable) {
    if (value == null) throw new NullPointerException();
    int hash = hash(key.hashCode());
    Segment seg = segmentFor(hash);
    //grab segment, and then call a function under a segment lock
    seg.put(key, hash, callable, true);

Segment {

   public(K key, int hash, Callable callable, boolean checkIfAbsent) {
     // if absent, then..

    try {

     //method executed under segment lock, return value put into map..
      put(key, hash, callable.execute());
   } finally {




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20100526/ba7a8836/attachment.html>

More information about the Concurrency-interest mailing list