[concurrency-interest] ConcurrentReaderHashMap kudos!

Elias Ross eross@m-Qube.com
Sat, 04 Dec 2004 21:20:20 -0800


On Sat, 2004-12-04 at 16:42, nnn6-twfe@spamex.com wrote:

> I would really like to have a ConcurrentReaderSortedMap and/or
> ConcurrentReaderSortedSet.  Some of our cache data structures need to
> maintain the most commmon sort order for performance reasons.  It really
> improves performance to maintain the data in sorted order in our case
> because there are 10000 readers for every writer, and most of the readers
> need the data in the same sorted order.  

The class SyncSortedMap will work, except in cases when you are
iterating.  Take a look at SyncCollection:  If you want to iterate for
several operations, I would create closures.  For example,

public abstract SyncMapOperation {
  public SyncMapOperation(SyncMap sm) {
    try {
      sm.readerSync().acquire();
      for (Iterator i = ssm.entryMap().iterator(); i.hasNext(); )
         operate((Map.Entry)i.next());
    } finally {
      sm.readerSync().release();
    }
  }
  public abstract void operate(Map.Entry me);
}

and then, if you want to print the list, for example, you would do this:

new SyncOperation(ssm) {
  public void operate(Map.Entry me) {
    System.out.println(me);
  }
};

It's fairly bug-proof and relatively clear when reading.  You'll
probably find this is the cleanest, compared to locking/unlocking for
each operation.  However, it will create a lot of interference if a
writer is waiting for a lock and the size of the data is large.

Alternatively, I would create a copy-on-write SortedMap if the data set
is fairly small.  (Around 1000-10000 or less entries.)

Or, you could save yourself some trouble and download
ConcurrentSkipListMap:

http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166x.jar
http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166xdocs/

You'd have to remove the 1.5 generics stuff and compile it for 1.3.  (I
sort of forgot this was around, but it's 1.5 so no free lunch for
you...)