The overall architecture of ConcurrentHashMap
This is the storage structure of ConcurrentHashMap in JDK1.8, which is composed of arrays,one-way linked list, red and black tree composition.
When we initialize a ConcurrentHashMap instance, an array of length 16 is initialized by default.
Because the core of ConcurrentHashMap is still the hash table, there must be hash conflicts. ConcurrentHashMap uses chain addressing to resolve hash conflicts.
If there are many hash conflicts, the length of the linked list will be long. In this case, the query complexity of data elements in ConcurrentHashMap will become O(n). Therefore, in JDK1.8, a red-black tree mechanism is introduced.
When the array length is greater than 64 and the list length is greater than or equal to 8, the single necklace list is converted to a red-black tree. In addition, with the dynamic expansion of ConcurrentHashMap, once the list length is less than 8, the red-black tree will degenerate into a unidirectional list.
ConcurrentHashMap is optimized for performance
It is mainly reflected in the following aspects:
In JDK1.8, the ConcurrentHashMap lock granularity is one node in the array, but in JDK1.7, the lock is Segment, the lock scope is larger, and therefore the performance is lower.
The introduction of red-black tree reduces the time complexity of data query. The time complexity of red-black tree is O(logn).
(As shown in the figure), when the array length is not enough, ConcurrentHashMap needs to expand the array. In the implementation of expansion, ConcurrentHashMap introduces the mechanism of multi-thread concurrent expansion. Simply put, after multiple threads fragment the original array, each thread is responsible for one fragment of data and this improves the efficiency of data migration during capacity expansion
In summary
There are many design ideas in ConcurrentHashMap that are worth learning and learning from.
For example, lock granularity control, segmented lock design, etc., they can be applied in actual business scenarios.