一、通过Key找到在Segment[]数组中的位置:
1. 变量定义:
ssize:
不小于concurrencyLevel的最小2的N次方, 默认concurrencyLevel等于16;
segmentShift:
32 - ssize从1左移的位数;
segmentMask:
ssize - 1;
key的hash方法
![](https://img.haomeiwen.com/i6351695/aa8e10d969684902.png)
2. 通过UnSafe获取Segment[]数组中下标为index的元素的地址
![](https://img.haomeiwen.com/i6351695/a0da8ef2112d8112.png)
3. 将Key放在HashMap的合适位置
3.1 由key确定在Segment[]数组中的下标
![](https://img.haomeiwen.com/i6351695/69ed9c138eee915f.png)
3.2 将Key插入到Segment中的合适的位置
① 获取key在table中的下标,记为index。
index = hash & (table.length - 1);
② 取table[index]的头部HashEntry,记为first。若first == null,表示table的index下标位置为null,新建一个HashEntry放置在table[index]的头部;若first != null,则进入③:
③ 从first开始沿链表遍历,若找到
(e.key == key || (e.hash == hash && key.equals(e.key))
则表示table中key已存在,用value替换oldValue,并返回oldValue;若直到链表的末尾也没找到,则构建新的HashEntry插入table[index]的链表头部。
3.3 put操作获取Segment的自旋锁的过程
![](https://img.haomeiwen.com/i6351695/b9f14d90c70a0b82.png)
4. UnSafe的常量
![](https://img.haomeiwen.com/i6351695/0a58afa077c54687.png)
网友评论