How concurrent Hashmap internally working in java?

Concurrent HashMap Internal Working

Concurrent HashMap: It allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.

Concurrency-Level: Defines the number which is an estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads.

Load-Factor: It is the threshold limit, used to control the resizing of the map.

Can we use Hashtable in this scenario?
No. Hashtable is thread safe but give poor performance in case of multiple thread reading from hashtable because all methods of hashtable including get() method is synchronized and due to which invocation to any method has to wait until any other thread working on hashtable complete its operation(get, put etc).

Can we use HashMap in this scenario?
No. Hashmap is not thread safe, so what will happen if one thread tries to put data and requires rehashing and at the same time other thread tries to read the data from hashmap, it will go in infinite loop.

ConcurrentHashMap(CHM) combines good features of hashmap and hashtable and solves performance and thread safety problem nicely.

ConcurrentHashMap added one Array on top of it and each index of this additional array represents complete HashMap. Additional array is called Segment in ConcurrentHashMap.

CHM doesn’t locks call for reading but it locks for writing.

Default size of Segment array is 16.


ConcurrentHashMap m = new ConcurrentHashMap(initialCapacity , loadFactor, concurrencyLevel);

ConcurrentHashMap m = new ConcurrentHashMap(200 , 0.75f, 10);

Initial capacity is 200, it means CHM make sure it has space for adding 200 key-value pairs after creation.

Load factor is 0.75, it means when average number of elements per map exceeds 150 (intital capacity * load factor = 200 * 0.75 = 150) at that time map size will be increased and existing items in map are rehashed to put in new larger size map.
Please read  on Load Factor for better understanding .

Concurrency level is 10, it means at any given point of time Segment array size will be 10 or greater than 10, so that 10 threads can able to write to a map in parallel.

Java Doc

Ankush Pahwa is an IT Majdoor (Labourer) in Indian IT industry for last 5 years. Don’t know what else to say, so stopping here.

Self-Learning -> Focused Group -> Learning Intensification -> Self-Learning

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :