[concurrency-interest] CopyOnWrite for Maps and other lists (not just ArrayList)

Kasper Nielsen kasper at kav.dk
Wed Dec 8 13:33:55 EST 2010


On 08-12-2010 18:30, Morgan Conrad wrote:

> I found it ironic/interesting that where java.util.concurrency uses
> actual classes for, say, CopyOnWriteArray, my code provides wrappers.

The purpose of CopyOnWriteArrayList is to allow for fast concurrent 
reads on the expense of fairly slow writes.

Your wrappers synchronizes all access to the underlying Map. Except for 
your iterators with takes a snapshot of the current data. 
CopyOnWriteArrayList does not take a snapshot when iterating. Instead, 
it creates a new array when somebody modifies it. Providing concurrent 
iterators access to the same underlying array.

If you were to implement something like a CopyOnWriteMap in a simple 
way. You would do something like this

class CopyOnWriteMap {
  volatile HashMap map=new HashMap();
  ReentrantLock lock = new ReentrantLock();
  public Object get(Object key) {
    return map.get(key);
  }

  public Object put(Object key, Object value) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
      HashMap newMap=new HashMap(map);
      Object o = newMap.put(key, value)
      map=newMap;
      return o;
    } finally {
      lock.unlock();
   }
  }
   .....
}

- Kasper


More information about the Concurrency-interest mailing list