1. HashMap
源码注释中有这么一句话:
In usages with well-distributed user
hashCodes
, tree bins are rarely used.
意思是说只要hash算法做得好,hash冲突少,红黑树基本用不上
属性值一览
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
// 默认的初始容量:16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量 2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
// 负载因子
// 作用是:假设现在初始容量为16,当往里put元素大于 16*0.75=12个时,hashmap就会进行扩容操作,容量变为之前的一倍,
// 而且之前put进去的值会进行rehash重新放到新的位置
// 负载因子太小了浪费空间并且会发生更多次数的resize,太大了哈希冲突增加会导致性能不好,所以0.75只是一个折中的选择
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/*
* 如果数组中某一个链表 >= 8 需要转化为红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/*
* 如果数组中某一个链表转化为红黑树后的节点 < 6 的时候 继续转为 链表
*/
static final int UNTREEIFY_THRESHOLD = 6;
/*
* 如果当链表元素 >= 8 并且数组 > 64 的时候转化红黑树
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 其实Node为Map.Entry的接口实现类。
* (Entry 为 Map 接口中的一个内部接口)
*/
transient Node<K,V>[] table;
// 记录键值对的个数
transient int size;
/**
* 记录集合中元素修改的次数
*/
transient int modCount;
/*
* threshold = 负载因子 * 数组长度
*/
int threshold;
}
内部类一览
// 链表形式的时候挂在某个位置的一个节点或者一串节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
// 下节点指针
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
// 当某一串的数量 >= 8, 而且当前map的总数量 > 64 的时候,这一串东西要转成红黑树
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
}
常用方法
put()
// put方法调用此方法往map中设置值
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table 为 null 新建一个table
if ((tab = table) == null || (n = tab.length) == 0)
// 调用 resize() 创建一个默认容量【16】的map
n = (tab = resize()).length;
//用hash值和数组长度计算数值下标
if ((p = tab[i = (n - 1) & hash]) == null)
//如果这个下标不存在元素则直接存储
tab[i] = newNode(hash, key, value, null);
else {
// 下标已经存在元素,进入else
Node<K,V> e; K k;
// 存在冲突
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 能进到这个循环就是说:不只是hash冲突问题,而是key都一模一样,所以后续要进行新值替换旧值得操作
e = p;
//如果和桶里第一个Node的key不相同,则判断当前节点是不是TreeNode(红黑树),如果是,则进
//行红黑树的插入
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 若是链表存储
else {
// 循环链表
for (int binCount = 0; ; ++binCount) {
// 直到链表尾部还未有重复 key
if ((e = p.next) == null) {
// 新建节点存储,把数据插入链表的最后边
p.next = newNode(hash, key, value, null);
// 若链表长度已经够了要进行红黑树转换的阈值,就转换成红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
// 若发现相同 key 则结束循环
// 能进到这个循环就是说:不只是hash冲突问题,而是key都一模一样,所以后续要进行新值替换旧值得操作
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 有重复的 key , 则新值 替换 旧值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// size在加完之后是否大于扩容阈值,是则需要进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
get()
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// tab 不为 null 同时 table 长度 > 0 同时数组对应下对应下标内容不为 null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 如果数组对应下标的第一个节点 key 和 查找的 key相同
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
// 返回第一个节点
return first;
// 不同, 同时还有其他节点
if ((e = first.next) != null) {
// 采用红黑树存储,查找树
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 链表形式, 遍历所有节点。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
// 没有则返回 null
return null;
}
resize()
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 已有table 长度是否 > 0
if (oldCap > 0) {
// table容量已经达到上限时拒绝扩容,原封不动的返回
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 没有超过最大空间,则容量扩大两倍,threshold也扩大两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else {
// 对map初始化时走入此分支
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 获取新的阈值
threshold = newThr;
// 基于新的容量 创建新的 Node 数组 和 哈希表
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// 遍历原有 table 重新计算每一个元素的位置
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// 对应的下标元素不为null
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 该数组下只有一个元素
if (e.next == null)
// 存储在新的数组上
newTab[e.hash & (newCap - 1)] = e;
// 红黑树存储
else if (e instanceof TreeNode)
// 将红黑树分离
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
// 获取链表的最后一个节点
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
遍历过程
遍历过程是无序的
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
// 当前的槽位
int index; // current slot
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
// 其他线程并发修改抛出 ConcurrentModificationException 略
// 当前槽位来到了最后一个节点,而且当前的槽位不是最后一个槽位的时候
// 去下一个槽位 (index++)
// 如果当前槽位有值,就从这个槽位继续开始往下遍历链表或者红黑树
// 如果没有值,继续下一个槽
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
二项分布
例题:
O型血在人群中的概率是35%,4个人中有2个人是O型血的概率是多少?
解答:
设A为O型, B为非O型(要么是要么就不是)
4人中 组合为 AABB的概率:
35% * 35% * ( 1- 35%)* ( 1- 35%)
AABB的全排列个数为:
C 4 2 C_{4}^{2} C42
所以两人为O的概率为:
C 4 2 × 0.3 5 2 × ( 1 − 0.35 ) 2 C_{4}^{2} \times 0.35 ^ 2 \times (1- 0.35)^2 C42×0.352×(1−0.35)2
二项分布就是重复n次独立的伯努利试验。在每次试验中只有两种可能的结果,而且两种结果发生与否互相对立,并且相互独立,与其它各次试验结果无关,事件发生与否的概率p在每一次独立试验中都保持不变,则这一系列试验总称为n重伯努利实验,当试验次数为1时,二项分布服从0-1分布。
二项分布概率的计算公式:
P
{
X
=
k
}
=
(
C
k
n
)
p
k
(
1
−
p
)
n
−
k
P \lbrace X=k \rbrace = (C_{k}^n)p^k(1-p)^{n-k}
P{X=k}=(Ckn)pk(1−p)n−k
期望计算:
E
(
X
)
=
n
p
E(X) = np
E(X)=np
泊松分布
当二项分布的n很大而p很小时,泊松分布可作为二项分布的近似,其中λ为np。通常当n≧20,p≦0.05时,就可以用泊松公式近似得计算。
HashMap
负载因子与泊松分布并没有什么关系。负载因子是影响哈希的散列情况、查找效率和resize的频率。
负载因子太小了浪费空间并且会发生更多次数的resize,太大了哈希冲突增加会导致性能不好,所以0.75只是一个试验后的折中的选择。
当二项分布中的 N 趋向于无穷大的时候,就可理解成hashMap
中的元素趋近于无穷大的时候,每个元素仍然有两种可能性:被访问或者不被访问。
假设每个元素被访问的概率为0.0001,当前元素个数为100000个,当使用二项分布计算时此计算有些复杂,此时我们就可以用泊松分布公式来计算这个元素被访问的概率。
2. TreeMap
常用方法
put()
public V put(K key, V value) {
// 第一次put, root为空,创建一个新树
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
// 创建新的节点
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
// 再往里put的时候
int cmp;
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
// 像是二叉搜索树那样插入新节点
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
// 像是二叉搜索树那样插入新节点
// 上边那个逻辑用了比较器,如果比较器为空
// 在此逻辑中直接用 compareTo 比较
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
// 调整红黑树
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
插入删除操作都需要维护整棵树的平衡,get()
,remove()
,都是O(logN)
的时间复杂度
3. LinkedHashMap
LinkedHashMap
是继承于HashMap
,是基于HashMap
和双向链表来实现的。
HashMap
无序;
LinkedHashMap
有序。
public LinkedHashMap(int initialCapacity,
float loadFactor,
// 这个boolean变量设置为true的话
// put和get操作已存在的Entry时,都会把Entry移动到双向链表的表尾。
// 而且会导致modCount++
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
如果是访问顺序,那put和get操作已存在的Entry时,都会把Entry移动到双向链表的表尾。
多线程程序的时候accessOrder = true
慎重慎重慎重!!!
类属性一览
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>{
/**
* The head (eldest) of the doubly linked list.
*/
transient LinkedHashMap.Entry<K,V> head;
/**
* The tail (youngest) of the doubly linked list.
*/
transient LinkedHashMap.Entry<K,V> tail;
// 内部类,before指向前一个,after
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
}
如何保证有序
当LinkedHashMap
调用put
方法的时候,会调用父类的HashMap
的put
// hashMap中的方法,
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// LinkedHashMap 重写此方法,使得在插入元素的时候,维护一个链表,记录插入顺序
tab[i] = newNode(hash, key, value, null);
// ...
}
// LinkedHashMap 重写的方法
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<>(hash, key, value, e);
// 就在此处进行链表的维护
linkNodeLast(p);
return p;
}
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
// 尾插法进行节点插入,遍历的时候方便获取插入的顺序。
p.before = last;
last.after = p;
}
}
// 初始化一个迭代器的时候,把next指向头结点
LinkedHashIterator() {
next = head;
expectedModCount = modCount;
current = null;
}
final LinkedHashMap.Entry<K,V> nextNode() {
LinkedHashMap.Entry<K,V> e = next;
// 慎重慎重开那个 accessOrder = true
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// ...
current = e;
// 往后遍历,所以有序
next = e.after;
return e;
}
关于get
一个元素也会导致此元素从原位置加到尾巴的设置
public LinkedHashMap(int initialCapacity,
float loadFactor,
// 这个boolean变量设置为true的话
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
// 设置为true,跳入判断,执行afterNodeAccess
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
// 把get的元素挪到最后一个
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
// get操作也算是 modCount ++ 了!!!!
// 多线程下慎重慎重慎重
++modCount;
}
}
4. WeakHashMap
4.1 Key
是弱引用
什么是弱引用请见 本人另一篇博客
/*
* Hash table based implementation of the {@code Map} interface, with
* weak keys.
* */
/*
* @Author 郭学胤
* @University 深圳大学
* @Description
* @Date 2021/2/14 20:53
*/
import java.util.*;
/* -Xms20M -Xmx20M */
public class test {
public static void main(String[] args) {
Map<Large, Integer> test = new WeakHashMap<>();
int i = 0;
while(i < 50){
test.put(new Large(),i );
i++;
}
}
}
class Large{
byte[] obe = new byte[1024*1024*5];
}
堆内存大小20M
,往堆中加入50个 5M
大小的对象,仍然不会OOM
,因为垃圾回收线程看到虚引用就给把虚引用指向的对象干掉了!
key是弱引用!!!!如果把大对象放在 Value 上一定会报错
4.2 常用方法
put()
public V put(K key, V value) {
Object k = maskNull(key);
int h = hash(k);
Entry<K,V>[] tab = getTable();
int i = indexFor(h, tab.length);
// 如果有哈希冲突,而且 key1.equals(key2),替换旧值
for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
if (h == e.hash && eq(k, e.get())) {
V oldValue = e.value;
if (value != oldValue)
e.value = value;
return oldValue;
}
}
modCount++;
Entry<K,V> e = tab[i];
// 采用头插法,插入节点,之前的节点接在这个节点下边
tab[i] = new Entry<>(k, value, queue, h, e);
// 当前容量到达阈值
if (++size >= threshold)
// 扩容两倍大小
resize(tab.length * 2);
return null;
}
resize()
void resize(int newCapacity) {
Entry<K,V>[] oldTable = getTable();
int oldCapacity = oldTable.length;
// 已经是最大容量不给扩容
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry<K,V>[] newTable = newTable(newCapacity);
// 把所有旧表的内容 rehash 到新表中
transfer(oldTable, newTable);
table = newTable;
/*
* If ignoring null elements and processing ref queue caused massive
* shrinkage, then restore old table. This should be rare, but avoids
* unbounded expansion of garbage-filled tables.
*/
if (size >= threshold / 2) {
threshold = (int)(newCapacity * loadFactor);
} else {
expungeStaleEntries();
transfer(newTable, oldTable);
table = oldTable;
}
}
ConcurrentHashMap
put()
JDK 1.8
之后已经从之前的分段锁变成了 CAS + synchronized
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
// 获取hash
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh; K fk; V fv;
// 如果当前的 tab 为空,初始化一张表
if (tab == null || (n = tab.length) == 0)
// 用CAS操作一个数字“sizeCtl”,操作成功的线程进行初始化工作
// 其余线程放弃CPU使用权,等到重新执行其他线程的时候,
// 已经初始化好了,while循环退出,从而结束这个方法的执行
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 当位置为空的时候使用CAS插入值
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
break; // no lock when adding to empty bin
}
// 进入这里的线程要么 CAS设置值失败,要么本来上边就有值,
// 反正不管怎么说这个槽位上已经有值了
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else if (onlyIfAbsent // check first node without acquiring lock
&& fh == hash
&& ((fk = f.key) == key || (fk != null && key.equals(fk)))
&& (fv = f.val) != null)
return fv;
else {
V oldVal = null;
// 上锁开始往表中设置值
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
// 在链表上进行KV节点的插入
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key, value);
break;
}
}
}
// 树上添加 K V 节点
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
else if (f instanceof ReservationNode)
throw new IllegalStateException("Recursive update");
}
}
if (binCount != 0) {
// 当前KV数量已经超过转换红黑树的阈值,
// 在方法内上锁进行本槽的树化
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
ConcurrentSkipListMap
内部类一览
SkipList
是个单链表
static final class Node<K,V> {
final K key;
volatile Object value;
// 指向下个节点的指针
volatile Node<K,V> next;
Node(K key, V value, Node<K,V> next) {
this.key = key;
this.val = value;
this.next = next;
}
}
// 当前调表的等级
static final class Index<K,V> {
final Node<K,V> node; // currently, never detached
// 指向下一层的节点
final Index<K,V> down;
// 指向右侧的节点
Index<K,V> right;
Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {
this.node = node;
this.down = down;
this.right = right;
}
}
常用方法
put()
private V doPut(K key, V value, boolean onlyIfAbsent) {
Node<K,V> z; // added node
if (key == null)
throw new NullPointerException();
Comparator<? super K> cmp = comparator;
for (;;) {
Index<K,V> h; Node<K,V> b;
VarHandle.acquireFence();
int levels = 0; // number of levels descended
// 第一次put 的时候会进入这个分支,因为头肯定为空
if ((h = head) == null) { // try to initialize
Node<K,V> base = new Node<K,V>(null, null, null);
h = new Index<K,V>(base, null, null);
b = (HEAD.compareAndSet(this, null, h)) ? base : null;
}
else {
// 再以后put的时候
for (Index<K,V> q = h, r, d;;) { // count while descending
// q 此时是 最高的索引头,当本层索引之后有右边的索引的时候
// r = 右边的那个索引
while ((r = q.right) != null) {
Node<K,V> p; K k;
// 如果此时右边的那个索引中的node为空,或者索引的key为空,或者索引的val为空
// 则此索引已经废掉了,把更右边的一个拉过来替换这个索引
if ((p = r.node) == null || (k = p.key) == null ||
p.val == null)
RIGHT.compareAndSet(q, r, r.right);
// 当前的这个索引的key比插入的这个小,继续向右找
else if (cpr(cmp, key, k) > 0)
q = r;
// 此时已经找到了,break
else
break;
}
// 刚刚已经找到了本层中比插入的这个大的索引,就是当前索引的右边的那个,
// 所以从当前索引往下找
// level++ 去下一层
if ((d = q.down) != null) {
++levels;
q = d;
}
else {
// 如果已经是最后一层,就在最后一层的真节点中继续找
b = q.node;
break;
}
}
}
if (b != null) {
Node<K,V> z = null; // new node, if inserted
/* 找到应该在哪里插入 */
for (;;) { // find insertion point
Node<K,V> n, p; K k; V v; int c;
// 找到空了都没找到应该插入的位置
if ((n = b.next) == null) {
if (b.key == null) // if empty, type check key now
cpr(cmp, key, key);
c = -1;
}
else if ((k = n.key) == null)
break; // can't append; restart
else if ((v = n.val) == null) {
// 如果节点的V已经为空了,则可以把这个节点删除了
unlinkNode(b, n);
c = 1;
}
else if ((c = cpr(cmp, key, k)) > 0)
// 继续寻找下一个位置,并且设置 c > 0
b = n;
else if (c == 0 &&
// c == 0 表示下一个节点已经不比插入的这个小了,可以就地插入
(onlyIfAbsent || VAL.compareAndSet(n, v, value)))
return v;
// 刚才 找到空了都没找到应该插入的位置 的时候设置了 c = -1
// 所以从最后插入,用CAS
if (c < 0 &&
NEXT.compareAndSet(b, n,
p = new Node<K,V>(key, value, n))) {
z = p;
break;
}
}
// 每次添加KV节点都有一定的概率生成索引,即往上抽取
if (z != null) {
int lr = ThreadLocalRandom.nextSecondarySeed();
if ((lr & 0x3) == 0) { // add indices with 1/4 prob
int hr = ThreadLocalRandom.nextSecondarySeed();
long rnd = ((long)hr << 32) | ((long)lr & 0xffffffffL);
int skips = levels; // levels to descend before add
Index<K,V> x = null;
for (;;) { // create at most 62 indices
x = new Index<K,V>(z, x, null);
if (rnd >= 0L || --skips < 0)
break;
else
rnd <<= 1;
}
if (addIndices(h, skips, x, cmp) && skips < 0 &&
head == h) { // try to add new level
Index<K,V> hx = new Index<K,V>(z, x, null);
Index<K,V> nh = new Index<K,V>(h.node, h, hx);
HEAD.compareAndSet(this, h, nh);
}
if (z.val == null) // deleted while adding indices
findPredecessor(key, cmp); // clean
}
addCount(1L);
return null;
}
}
}
}