Java Concurrency and Add-Only HashMaps

I am writing a program that makes extensive use of large HashMaps. It is multithreaded, so I used read and write locks when accessing it. However, it has a special property that I would like to use.

After the data is "placed" in the HashMap, this data never changes. Ever. Whenever there is a change in the state of this data structure, in fact, it simply creates a new β€œgeneration” of the structure, leaving the old whole.

That is, is it safe to read the value from the HashMap at the same time that the other thread is writing the value, knowing that the other thread will never write the value you are reading? Is there any simple hash table that will give me such a guarantee?

+4
source share
4 answers

The problem is not the hashmap IN data, but that you change the hashmap itself when you insert something; its structure. You cannot do this with multiple threads at the same time as the standard HashMap.

The compatible java package offers thread-safe hashtmap:

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html

Internally, it will use non-blocking thread safety methods.

+1
source

Not really. Since you can write to it, you can cause the base array to resize when you do this. If you cause a resize in the middle of another stream, read it, you really will randomly find the data for sure!

+2
source

I know that you stated that it will not be overwritten, but you should think about ConcurrentHashMap, if only because you no longer need your lock code.

This special map (since java 1.5) ensures that you never get a ConcurrentModificationException, because it will return you the last "full" record.

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html

It is also ultrafast for multiple simultaneous readings. See this article for more information:

http://www.ibm.com/developerworks/java/library/j-jtp07233/index.html#N101CD

Other notes: it does not allow null keys / values, and it has another convenient putIfAbsent method.

NTN

+1
source

Instead of HashMap, you can use persistentMap, then each author will have to block it when adding a new object and replace the link to the map with a new one, but readers can always read from the "current" version (possibly not finding the value they are looking for, because it added at the same time.

Please note that reading and writing a map link must be atomic.

0
source

All Articles