【Java集合】JDK1.8HashMap+Concurrenthaspmap源码
HashMap
一、前提
·JDK1.7 HashMap由数组+链表实现
·JDK1.8后 HashMap由数组+链表+红黑树实现(提高查找效率,红黑树有序近似平衡,可用二分查找)
·数据以K-V形式存储,但又不都存储于数组中,数组中存储K值,下面还会对应存储value,hash值,next指针
·树化条件:链表长度大于等于8 且数组长度大于等于64
·扩容条件:达到原数组容量的0.75,进行扩容
·HashMap是线程不安全的,在resize和移动元素过程中可能产生覆盖问题,到不会造成死循环,想保证线程安全用Concurrenthashmap
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;
}
JDK1.8
·红黑树
- 平衡二叉树
- 最长路径不超过最短路径两倍
- 每一条搜索路径有相同的黑色节点
- 任何一个路径上不能存在连续的两个红色/黑色节点,所有叶子节点都是黑色
·树化,退化由参数决定(后面详细说)
·数组初始容量是2的n次幂, 一是方便进行与运算(putVal方法),二是为了扩容后方便元素整体移动,算法导论中也有提及
二、重要的参数
/**
* The default initial capacity - MUST be a power of two.// 这里数组长度必须是偶数
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 初始数组容量大小为16
static final int MAXIMUM_CAPACITY = 1 << 30;// 最大数组容量2^30
static final float DEFAULT_LOAD_FACTOR = 0.75f;// 加载因子,像水桶装水,快满还没有满时,拿来一个新的空桶,控制什么时间进行扩容,因为扩容也需要时间,当size大于0.75f时会扩容,0.75也是经过大量统计计算得出的,是空间与时间的平衡
static final int TREEIFY_THRESHOLD = 8;// 链表转成红黑树的阈值,树化
static final int UNTREEIFY_THRESHOLD = 6;// 红黑树转成对应链表的阈值,反树化
static final int MIN_TREEIFY_CAPACITY = 64;// 整体节点各数超过64才可以树化
// 源码中显示8和6符合泊松分布
三、hash函数
// 整数的hash等于本身
static final int hash(Object key) {
int h;
// 为了散列平衡,不浪费空间,把高位和低位进行异或操作
// 这是一个扰动函数
// >>>表示右移后左边补0 所以就是32位h的高16位和低16位
// ^是异或 00 11为1 01 10为0
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
四、putVal方法
// 在new Hash()时,若没有参数,走无参构造方法,是不会创建数组的,只有调用put方法,才会创建数组
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// 这里创建了一个空数组,用来存放Node节点
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table初始是空的node数组,tab也为空,
if ((tab = table) == null || (n = tab.length) == 0)
// resize方法很重要,初始化,扩容,扩容是必须是2倍,方便移动
// 经历过resize方法,n值为当前数组的长度
n = (tab = resize()).length;
// 与运算效率更高,所以不用取模运算,初始时这里的值也一定为空
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);// 把对应元素放到Node节点,给到tab数组
else {// 有数据时执行下面三种方式,第二次put数据时上面进不去走这个
Node<K,V> e; K k;
/* 此时获得一个由hash值相同的元素组成的链表 链表的首节点是p
* 可能出现两种情况
* ==p是树节点和p不是树节点==
* 树:putTreeVal 红黑树插入之后返回旧数据 如果没有返回空
* 链表:我们循环检查链表中的value和key是否equals
* 遍历到尾部就会添加新节点 返回的e就为null
* 插入新节点 并判断是否达到TREEIFY_THRESHOLD值
* if-else用来判断三种情况
* 1. 判断p就是要找的节点
* 2. 判断p是树节点,则调用putTreeVal方法,如果有旧数据就返回给e,否则返回null
* 3. 此时只剩下检索链表,用到死循环,判断是否大于等于TREEIFY_THRESHOLD树化,或者小于值进行链表添加
*/
// 这种情况针对于key相同的值添加,用后面的值覆盖原来的key对应的值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;// e指向旧节点
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {// 无终止条件,死循环的哇
// p.next是数组引出的链表
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果长度大于等于7,就树化
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 在treeifyBin方法中判断*数组*长度是否小于64,不小于就树化,刚好两个条件都判断到了
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;// 此时e为p,把旧值赋给oldValue用于存储
if (!onlyIfAbsent || oldValue == null)
e.value = value;// 赋值新值
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)//The next size value at which to resize (capacity * load factor).
resize();// 扩容
afterNodeInsertion(evict);
return null;
}
五、resize方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 初始时参数为null或0
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 初始时这个函数进不去
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 左移1位乘2,新的等于老的*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 新数组容量在老数组上乘2
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 最初在这里执行,newCap值为16
newCap = DEFAULT_INITIAL_CAPACITY;
// 最初扩容时阈值为12
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);
}
// 上面的newThr给到全局的阈值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 这里才是第一次创建16个空间的Node数组
// 后面扩容也是走过这步,将上面的值传过来,表示创建新的数组长度
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab; // 给到全局数组对象
// 创建新数组时要把老数组的元素移动过来,这个是判断老数组,后面进行移动
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// 取出数组对象
if ((e = oldTab[j]) != null) {
oldTab[j] = null;// j对应的链表用e指向,e的next为j,但是后面没有链表的值了,所以置为null
// 根据上面的数组对象取出下面的桶也就是链表
if (e.next == null)// 能进来表示数组只有一个元素
newTab[e.hash & (newCap - 1)] = e;// 直接把e给到数组中,相当于1,1和1,2
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 高位低位头元素,尾元素
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
// 下面是do-while整体数据迁移过程,每次都是迁移一个数组对象对应的下面的一个链表
do {
next = e.next;
/**
*这里处理的非常好,用e.hash与上老链表中的值,e.hash不变,假设初始是16
*由于扩容了一倍,长度为32,则需要看低五位
*那么看他的倒数第五位是0还是1
*是0表示加一后没有变化仍像旧表中一样,在一个链表中
*是1则表示加一后一定去了新的链表中,而且存储在新数组的后半段
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;
}
六、resize方法中do-while代码图解
七、JDK1.7中为什么会有死循环?
根本原因:头插法
Concurrenthashmap
面试常问:数据结构、参数、源码、扩容流程、CAS+synchronized、volatile,2^n
Concurrenthashmap源码也就6k多行,不要慌嘛~(手动狗头)
一、与HashMap的共同点
二者都不是在new时用构造方法创建固定空间,是调用put方法是才创建数组
二、重要参数
// 有很多和HashMap中一致的,不做解释
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final int DEFAULT_CAPACITY = 16;
// 没有见过Array的类吧,所以类加载需要一些信息,这8代表头信息或源数据信息
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
private static final float LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
private static final int MIN_TRANSFER_STRIDE = 16;
private static int RESIZE_STAMP_BITS = 16;
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
三、putVal方法
// 扩容移位和hashmap的一致
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {// 又是一个死循环
Node<K,V> f; int n, i, fh;
// 首次进来tab为空
if (tab == null || (n = tab.length) == 0)
tab = initTable();// 初始化表,initTable方法中有个sizeCtl,是扩容标志位,如果为-1,代表初始化,如果是-(n+1)表示扩容,其他情况表示扩容的阈值
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {// 判断要插入的key值对应的位置是否为空,这一步处理的十分巧妙啊~
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
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;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
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;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);// addCount首先判断是否需要扩容
return null;
}
四、initTable初始化方法
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
// sizeCtl根据new时给的值会改变
// 这里保证了线程安全,如果sizeCtl不大于0,其他线程进来只能等待
// 第一次不大于0进来的线程会执行去static方法中,获取当前字段属性值,为了获取当前属性空间的偏移量,赋给sizeCtl,这时其值就改变了
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
// 数组初始化,保证一直都是只有一个线程初始化操作
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;// 第一次n表示16,初始数组容量
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
五、transfer方法
(这个方法太吊了,面试随便问一个都会死,加油只有头秃才能变强)
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
// NCPU根据电脑硬件决定,四核八线程,NCPU值就为8
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
// 原来有16个长,转移后要从第16位置的数组开始,把原来数组长度给transferIndex,由后向前逐渐遍历,不然不知道i++,加到多少合适,每次都得判断,这样n--更容易一些
transferIndex = n;// 偏移量的值
}
int nextn = nextTab.length;
// 桶中指定hash值为-1,如果桶中值已经是forward过的了,不需要转移工作,类似于标志位
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
// 死循环,表示迁移开始啦
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) {
int nextIndex, nextBound;
// 第二次i==14,没有值就跳过去,之后一直--i,
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
// 第一次一定走这个判断也只有第一次能进来,比较nextIndex和transferIndex
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;// bound表示最小下标
i = nextIndex - 1;// i表示最大下标,一直到i==bound,完成迁移工作
advance = false;
}
}
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
// 前面判断后,如果有值,跳转到这里,实际数据迁移工作
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {// fh表示当前节点表示的hash值
int runBit = fh & n;// 等于0
Node<K,V> lastRun = f;// 表示当前节点
// 一直进行遍历操作,给节点值为0或1
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {// 这里判断是0还是1,0是原位置,1是新位置
runBit = b;
lastRun = p;// 最后值相同的节点,以后的元素就不用重新判断了,一定是一致的,面试问过
}
}
if (runBit == 0) {
ln = lastRun;// ln低位链表,等于0的放低位链表
hn = null;// hn高位链表,等于1的放高位链表
}
else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
setTabAt(nextTab, i, ln);// 是0的直接放i
setTabAt(nextTab, i + n, hn);// 是1的直接放i+n位置,把之前的让出来了
setTabAt(tab, i, fwd);// 把原数据进行转发,以后从新位置开始取
advance = true;
}
else if (f instanceof TreeBin) {
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
六、原来数组长度是128,扩容后是256,难道需要单线程完成整体元素的迁移工作吗?
肯定是要用多线程方式运行,且数据不可以乱,将原来的数组分段给每个线程最少负责16个桶的迁移工作,8个线程可以并行执行,小于16个桶,那么直接使用单线程运行即可。
参考资料
https://www.bilibili.com/video/BV1854y1479o?p=1
https://blog.csdn.net/qq_45117655/article/details/109532403