,

Monday, 26 January 2015

Internal Working of ConcurrentHashMap

What is the internal data structure of ConcurrentHashMap ?
ConcurrentHashMap has Segment array which contains Entry array. Entry is singly linked list.
Let us understand the same in detail.

Demo 1:

package com.a.b;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author Ganesh.Rashinker
 *
 */
public class MainClass {
public static void main(String[] args) {
//What is the internal datastructure of ConcurrentHashMap
ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>();
}
}




When you create a ConcurrentHashMap using its default constructor , the default initial capacity is 16  , load factor is 0.75 and concurrency level is also 16. Initial capacity and load factor are associated with Entry table [] and not the segements. Concurrency level is associated with the number of segments.

Demo2 illustrates how initial capacity is associated with Entry table array.

Demo 2:

package com.a.b;
import java.util.concurrent.ConcurrentHashMap;
/**
 *
 * @author Ganesh.Rashinker
 *
 */
public class MainClass3 {
public static void main(String[] args) {
ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>(63);
}
}



We have created ConcurrentHashMap using the syntax
ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>(63);
In this case , the number of segments does not change it is the default 16 Segments whereas the number of elements in Entry table array is 04 in each segement(Four buckets in each Segment) so as the ConcurrentHashmap has 64 buckets. These Entry table array has load factor 0.75 , so when the individual Entry table reaches the threshold ie 3 in our case the Entry table array size will double and become 08 for that Segment.

Now let us understand how concurrency level is accociated with Segment.

Demo 3:

package com.a.b;
import java.util.concurrent.ConcurrentHashMap;
/**
 *
 * @author Ganesh.Rashinker
 *
 */
public class MainClass2 {
public static void main(String[] args) {
ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>(65, 0.75F, 63);
}
}



We have created ConcurrentHashMap using the syntax
ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>(65, 0.75F, 63);
The number of Segments is 64 The number of Entry table array(buckets) in each segment is 02 which is taking care of initial capacity 65. To take care of the initial capacity of 65  , 128 buckets are created in all.

Conclusion : 
The internal datastructure of ConcurrentHashMap is Segment array of Entry array. Entry array is bucket in concurrent hashmap and Segment is taking care of number of threads which is nothing but concurrency level.


No comments:

Post a comment