2

I have a map that is frequently read but rarely write to. Some operations (can be reading or writing) involves multiple objects that needs to be operated atomically, so I used a ReadWriteLock to improve performance.

Now I have the option to downgrade the concurrent map to a normal hash map, but I am concerned about some of the slow iteration code.

If I downgrade the map, the long iterators to must hold the read lock to avoid concurrent access exceptions. I think this will block the writing threads for too long.

Since some of the iterators are not sensitive to inconsistent data, I can keep the concurrent map so that iterators can be used with concurrent writes. However, this adds unnecessary overhead (from the concurrent map) to operations that are properly using the locks.

Alternatively, I can implement something like a Read-on-write map, where the entire (non-concurrent) map is cloned for a write operation so that existing iterators continues to work outside a read lock.

Obviously, all these methods are valid and the performance depends on the actual code and setup. However, I am wondering is there any study on this (so I don't have to do the experiments myself)?

billc.cn
  • 7,187
  • 3
  • 39
  • 79
  • 1
    here is one link that tell performance difference between hashmap and concurrent hashmap. http://www.ibm.com/developerworks/java/library/j-jtp07233/index.html – Ravi Bhatt Aug 10 '12 at 10:49

1 Answers1

5

I have a map that is frequently read but rarely write to.

In that case I would consider implementing a copy of write map. e.g.

private final Map<Key, Value> map = ?* thread safe map */
private volatile Map<Key, Value> mapCopy = emptyMap();

// when you write
get lock
modify map
take a copy and store it in mapCopy
release lock

// when you read
Map<Key, Value> map = this.mapCopy;
use map

As you can see, you never need to obtain a lock on a read, only on a write.

If I downgrade the map, the long iterators to must hold the read lock to avoid concurrent access exceptions. I think this will block the writing threads for too long.

Instead of guess, I suggest you measure it.

I am wondering is there any study on this

I wouldn't take such a study too seriously if it did. As you suggest the result vary based on your situation.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I am hoping someone did some study like when the map size is this large and the access pattern is like this, then the performance of the implementations are like that, but maybe I am asking for too much. I do agree with you that copy-on-write map seems to be slightly more efficient. – billc.cn Aug 10 '12 at 10:57
  • CopyOnWriteArrayXxxx collections use this approach. When considering map size you would need to look at the complexity of the keys and values e.g do they need to be deep copied? – Peter Lawrey Aug 10 '12 at 11:01
  • If you think it would be useful, you could publish such a report as an article. ;) – Peter Lawrey Aug 10 '12 at 11:01