Do you know the underlying implementation of ConcurrentHashMap?What is the implementation principle?

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.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值