Home United States USA — software Java Hashtable, HashMap, ConcurrentHashMap: Performance Impact

Java Hashtable, HashMap, ConcurrentHashMap: Performance Impact

208
0
SHARE

This article compares the performance behaviors between the data structures HashMap, Hashtable, and ConcurrentHashMap through practical examples.
Join the DZone community and get the full member experience. There are a good number of articles that articulate functional differences between HashMap, Hashtable, and ConcurrentHashMap. This post compares the performance behavior of these data structures through practical examples. If you don’t have the patience to read the entire post, here is the bottom line: when you are confronted with the decision of whether to use HashMap, Hashtable, or ConcurrentHashMap, consider using ConcurrentHashMap since it’s thread-safe implementation without compromise in performance. To study the performance characteristics, I have put together this sample program:
This program triggers multiple threads to do a concurrent read and write to the java. util. HashMap. Let’s walk through this code. The primary object in this program is myHashMap, which is defined in line #7. This object is of type java. util. HashMap and it’s initialized with 1000 records in the method initData(), which is defined in line #9. Both the key and value in the HashMap have the same integer value. Thus this HashMap will look as shown in the below diagram:
Data in the HashMap
The Writer Thread is defined in line #19. This thread generates a random number between 0 to 1000 and inserts the generated number into the HashMap, repeatedly, 10 million times. We are randomly generating numbers so that records can be inserted into different parts of the HashMap data structure. Similarly, there is a Reader thread defined in line #35. This thread generates a random number between 0 to 1000 and reads the generated number from the HashMap.

Continue reading...