JDK1.8 HashMap put源码剖析

==> 学习汇总(持续更新)
==> 从零搭建后端基础设施系列(一)-- 背景介绍


从一个最简单的例子开始剖析hashmap的源码

Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
     map.put(i, i);
 }

内部都发生了什么? 跟着put方法进去看看

public V put(K key, V value) {
 	return putVal(hash(key), key, value, false, true);
}

hash(key)这个方法是干嘛的? 继续跟着hash(key)进去看看

static final int hash(Object key) {
 	int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

咋一看,看不太懂,(h = key.hashCode()) ^ (h >>> 16)这个的目的是什么?

OK,让我们分析一下,key.hashCode(),对应的是Integer的hashcode,那么Integer的hashcode是什么呢?接着去看看Integer是怎样重写的hashcode。

@Override
public int hashCode() {
    return Integer.hashCode(value);
}

public static int hashCode(int value) {
  	return value;
}

Soga,原来Integer的hashcode就是int的值啊,OK,那现在h=key.hashCode()的值就知道了

那为什么h=key.hashCode()要和它的低16位(h>>>16)异或呢? 这个后面再说,我们带着这个疑问继续往下探一探。

好,我们现在假装已经把hash这个方法看完了,并且知道它返回了一个hash值,其实就是一个整数嘛

现在我们来看一下putVal的入参

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)

提前透露一下,后面两个参数我们现在不需要关心,所以,假装看不到它。

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)
            tab[i] = newNode(hash, key, value, null);
        else {
        	   ……
        }
        ……
 }

我们先从最简单的看起,后面的现在这个例子也走不到,所以当它是空气,不?它。

首先,第一个if ((tab = table) == null || (n = tab.length) == 0),table==null的情况只有一种,那就是map被new出来之后,还没有put数据,大家可以看一下hashmap的构造函数,都没有对table进行初始化,对吧?
PS:(n = tab.length) == 0这个东东到底是什么时候会触发啊???把相关源码都看一遍了,也没发现,好不爽。。。不会是写着玩的吧,,,哪位大神如果知道的话,能否评论一下。。。

OK,现在我们知道hashmap的初始化已经集成到resize这个方法里面了。

接着看第二个if ((p = tab[i = (n - 1) & hash]) == null),咋一看,这是什么鬼,那我们先从最里面的(n - 1) & hash说起,这其实就是 hash % (n-1),看下面

a = 7, b = 14, c = 8
现在,分别求a % c和 b % c,将它们转成a & (c - 1) 和 b % (c - 1)
7 & (8 - 1)
0111
0111
-------
0111
=7

14 & (8 - 1)
1110
0111
------
0110
=6

是不是看出什么规律了,其精髓就是,将2的N次方-1后,除了最高位变为0,低位全部为1,那么这时候,任何数 A &(2^N - 1)得到的结果都是A的低N位。

PS:现在知道为什么h^h>>>16,低16位和高16位异或了吧?那就是让高16位的变化,反应到底16位上,这样才可以防止极端情况下,出现大量的hash冲突!

所以 tab[i = (n - 1) & hash]的意思就很明显了,当定位到的桶 == null的时候,说明这个桶是空的,是可以放数据的,最后tab[i] = newNode(hash, key, value, null)

接下来就是分析,如何处理冲突的,再来个case

Map<Integer, Integer> map = new HashMap<>();
Random random = new Random();
for (int i = 0; i < 1000000; i++) {
   map.put(random.nextInt(10000000), random.nextInt(1000000));
}

现在终于可以将putVal的源码上齐了

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)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            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;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

OK,现在终于发生冲突了,先分析第一个if
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))

  • p.hash == hash && p.key == key,说明了,hash相同的情况下,key也是可以不相同的
  • ((k = p.key) == key || (key != null && key.equals(k))),如果key是一个复合类型的对象,那么需要用equals方法判断是否相等,而equals是可以自由重写的。

提问:如果put key后,改变key的hash值,会发生什么?

如果重复put同一个key的话,那么我们看最下面那个if

if (e != null) { // existing mapping for key
    V oldValue = e.value;
    if (!onlyIfAbsent || oldValue == null)
        e.value = value;
    afterNodeAccess(e);
    return oldValue;
}

如果e!=null,那么就判断,是否需要更新值?
PS:afterNodeAccess和afterNodeInsertion是有大用处的,但是对于现在又一丢丢用都没有

接着分析第二个if
if (p instanceof TreeNode)
判断这个桶是不是红黑树节点
如果是,那么就XXX, 现在进去putTreeVal这个方法看看
此处省略1千万个字,以表达我弱鸡的N次方……

接着分析最后一个else
如果该桶是一个链表,那么

  • 遍历到链表末尾,如果此时节点数大于等于7(TREEIFY_THRESHOLD - 1),就将链表转为红黑树。
  • 遍历的过程中,发现有相同的key,那么就停止遍历跳出去到if(e != null)那里。

OK,put的方法已经分析到结尾了,就剩下两个,一个是++modCount,这个到底是干嘛的?一个是resize()

好的,我们先说++modCount
此处省略100W个字,,,不是我菜,是留着讲另一个知识点的时候再说。

最后,我们来see see resize这个方法,挺有意思的,还能引出不少的点。

先来分析如何重新计算newCap和newThr

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        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;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                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 = 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;
       ……
    }

是不是咋一眼看去,WC,重新计算两个参数,给我整这么一大段。。。嘴里噼里啪啦一顿,但是身体还是很诚实的看了下去。。。

其实这还不是初始化集成到resize方法惹的祸。。。

接下来看 int oldCap = (oldTab == null) ? 0 : oldTab.length

这一步就是为了初始化做的,如果oldCap=0,那么就直接跳过第一个if判断了,现在我们来分析这几种情况

  • oldCap=0,oldThr=0,这种情况是new HashMap<>()导致的,因为不指定初始容量的话,是不会初始化threshold的。然后跳到最后一个else里,就会初始化默认值
newCap = DEFAULT_INITIAL_CAPACITY;//16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//0.75 * 16
  • oldCap=0,oldThr > 0,这种情况就是new HashMap<>(n)导致的,指定了初始化容量,就会初始化阈值,初始化阈值的时候,还有个有趣的方法,这里我就不分析了,这个方法的功能是返回离cap最近的2的N次方整数,例如cap=6,返回8
static final int tableSizeFor(int cap) {
   int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
  • oldCap>0,oldThr=0 或 oldThr > 1,这种情况是已经put数据了,那么会进行以下判断
    1. 如果oldCap > MAXIMUM_CAPACITY(1 << 30),就不再扩容,并且threshold = Integer.MAX_VALUE
    2. 如果oldCap * 2 < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY 就可以设置新的newThr = oldThr << 1
if (newThr == 0) {
  float ft = (float)newCap * loadFactor;
  newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
            (int)ft : Integer.MAX_VALUE);
}

这一段,就是处理当oldCap<16的时候的情况

OK,重新计算newCap和newThr分析完了,下面就是分配新的空间。然后重新洗牌。

final Node<K,V>[] resize() {
        ……
        @SuppressWarnings({"rawtypes","unchecked"})
        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;
                    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 { // preserve order
                        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;
    }

和put的时候差不多,都是三部曲,要么是普通的node,要么是红黑树,要么是链表

  • 普通的node处理,newTab[e.hash & (newCap - 1)] = e,相当于是重新洗了一遍牌。
  • 红黑树,此处省略1亿个字,爱咋地咋地。
  • 链表,这个就比较有趣了,具体看注释
//设lo为链表A,hi为链表B
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
    //取出下一个节点
    next = e.next;
    //oldCap是2的N次方,所以它肯定只有一位为0
    //那么e.hash&oldCap是不是相当于随机的01出现呢?
    //所以这里这么做就是为了均匀切分链表为AB两个链表! 
    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);
//原位置就用A链表代替
if (loTail != null) {
    loTail.next = null;
    newTab[j] = loHead;
}
//j + oldCap位置就放置B链表,这样是不是相当于将链表打散了?
if (hiTail != null) {
    hiTail.next = null;
    newTab[j + oldCap] = hiHead;
}

提问:高并发下hashmap会发生什么情况?(1.7和1.8),先说答案,1.7和1.8都有可能发生XXX,但是发生的位置不一样。

好了,put方法就简单说到这里。有问题,或者有另外的见解的,欢迎讨论!本人专门承接各种疑难杂症,但是不包治,哈哈哈。

原创文章 257 获赞 277 访问量 69万+

猜你喜欢

转载自blog.csdn.net/qq_18297675/article/details/94230565