Analysis of the difference between HashMap, HashTable and ConcurrentHashMap

table of Contents

1. The underlying principle

Two, the difference


1. The underlying principle

The bottom layer of HashMap is composed of a linked list and an array. When the length of the linked list exceeds 8, the linked list is converted into a red-black tree.

Why is the number of Map buckets more than 8 before being converted to red-black trees?

TreeNodes occupies twice the space of ordinary Nodes. In order to balance the space and time, red-black trees are faster than the linked list at 6 o'clock, but the conversion process and space consumption are not cost-effective; the distribution frequency of nodes will follow the Poisson distribution, and the length of the linked list The probability of reaching 8 elements is 0.00000006, which is almost impossible.

Why is the threshold value 8 converted into a red-black tree different from the threshold value 6 converted into a linked list? In order to avoid frequent back and forth conversion consumption performance.

HashTable: inherited from Dictionary, can not store null keys and values, thread safe,

ConcurrentHashMap: The bottom layer is implemented by segmented array + linked list, thread-safe, using segmented lock technology, inherited from AbstractMap, and cannot store null keys and values.

Two, the difference

1. Both the key and value of HashMap can be null, while HashTable cannot;

2. HashMap is not thread-safe, HashTable is thread-safe;

3. The default capacity of HashMap is 16; each time the capacity is increased, the capacity is changed to "original capacity x2"; the default capacity of Hashtable is 11; when the capacity is increased, the capacity is changed to "original capacity x2 + 1" each time ".

4. The load factor of HashMap and HashTable is 0.75.

5. Hashtable's synchronized is for the entire Hash table, that is, each time the entire table is locked to allow the thread to monopolize. ConcurrentHashMap allows multiple modification operations to be performed concurrently. The key lies in the use of lock separation technology.

6. The expansion of ConcurrentHashMap belongs to the expansion triggered by the elements in the segment exceeding 75% of the corresponding Entry array length of the segment, and the entire Map will not be expanded (the detection before insertion does not require expansion, which effectively avoids invalid expansion).

 

Guess you like

Origin blog.csdn.net/weixin_42228950/article/details/100859766