HashMap 源码分析

简介

JDK1.7:

1.数据结构是数组加链表
2.在并发的情况,发生扩容时,可能会产生循环链表,在执行get的时候,会触发死循环,引起CPU的100%问题
3.在并发的情况会产生数据丢失

JDK1.8

1.数据结构是数组加链表、红黑树
2.在并发的情况会产生数据丢失

image

数据结构

Hash散列结构

用于将 key 的 hashCode 映射为数组上的角标

// 拿到key的hash值后与其无符号右移16位取与
// 通过这种方式,让高位数据与低位数据进行异或,以此加大低位信息的随机性,变相的让高位数据参与到计算中。
 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
// 获取到处理后的Hash值后计算数组中的位置
// n 为数组的长度即 length,index 为数组中的位置
index = hash % n

//和上面的算法相同,但效率高
index = (n - 1) & hash 

为什么 hash 对 length 取余就能得到数组角标?
因为 hash 对数组的长度取余,那么得到的数一定在数组长度范围之内

所以 index 和数组长度有关
这也是为什么当数组长度变化后,所有的元素都要重新计算位置。

数组结构:

存储链表或红黑树的首个节点

单向链表结构:
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;
    }

    // getter and setter ... toString ...
    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

红黑树结构:

LinkedHashMap.Entry 继承自 HashMap.Node ,所以 TreeNode 继承自 上面链表结构的 Node

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;
        }
    }

源码分析

变量说明

注意:这里的容量指的是数组的容量也是HashMap的容量,而 size 字段则代表HashMap当前存储的数据量,即HashMap中键值对的数量

/**
 * 默认初始容量16(必须是2的幂次方)
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

/**
 * 最大容量,2的30次方
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认加载因子,用来计算threshold
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 链表转成树的阈值,当桶中链表长度大于等于8时转成树 
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 进行resize操作时,若桶中数量小于等于6则从树转成链表
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 桶中结构转化为红黑树对应的table的最小大小

 当需要将解决 hash 冲突的链表转变为红黑树时,
 需要判断下此时数组容量,
 若是由于数组容量太小(小于 MIN_TREEIFY_CAPACITY )
 导致的 hash 冲突太多,则不进行链表转变为红黑树操作,
 转为利用 resize() 函数对 hashMap 扩容
 */
static final int MIN_TREEIFY_CAPACITY = 64;
/**
 保存Node<K,V>节点的数组
 该表在首次使用时初始化,并根据需要调整大小。 分配时,
 长度始终是2的幂。
 */
transient Node<K,V>[] table;

/**
 * 存放具体元素的集
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * 记录 hashMap 当前存储的元素的数量
 */
transient int size;

/**
 * 每次更改map结构的计数器
 */
transient int modCount;

/**
 * 用于判断是否需要扩容
 * threshold = capacity * loadFactor
 * 
 * 如果 size > threshold 则进行扩容
 * 这里的size是指HashMap 的size不是数组的长度
 *
 */
int threshold;

/**
 * 加载因子:用于计算threshold
 */
final float loadFactor;

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;
        //判断当前 hash 计算后数组位置上的元素是否为空
        if ((p = tab[i = (n - 1) & hash]) == null)
            //当前位置没有元素这直接将 Node 放入即可
            tab[i] = newNode(hash, key, value, null);
        else {
            //该位置已经有元素了,解决hash碰撞

            Node<K,V> e; K k;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                //当前传入的key 和 当前位置上的key 是同一个,说明只要修改值就行了
                e = p;
            else if (p instanceof TreeNode)
                //当前传入的key 和 当前位置上的key 不是同一个,且当前节点为红黑树节点,将传入的元素加入红黑树
                e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //当前传入的key 和 当前位置上的key 不是同一个,且当前节点不是红黑树,那就是链表结构
                //遍历链表,插入传入的元素
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        // 如果p的next为空,将传入的元素添加到链表后面
                        p.next = newNode(hash, key, value, null);
                        //如果链表长度大于等于8 则转化为红黑树
                        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;
                //根据规则选择是否覆盖value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // size自增后大于扩容阈值,进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

首先根据key的哈希值计算出 Node 应该存放在数组什么位置
但是可能会出现哈希冲突,所以当两个不同的key
其哈希是一样的,那么他们存放在数组中的位置就是相同的,这时候会将这两个Node用链表的结构存放,但是当数组中一个位置的链表元素大于等于8个时,链表插入的效率贬低,此时链表结构会转换为红黑树

image

扩容机制

添加元素时,如果 size > threshold 则进行扩容,size 为HashMap当前存储的数据量,

  final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;//默认值为0,如果在HashMap构造函数中传入了数组的容量,会给 threshold 赋值
        int newCap, newThr = 0;
        
        /* ① 根据原先数组的容量和阈值计算新的容量和阈值 **/
        if (oldCap > 0) {//数组容量大于0 
            if (oldCap >= MAXIMUM_CAPACITY) {//数组容量大于等于最大值,不进行扩容了
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //扩容一倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //如果扩容后小于最大值 而且 旧数组桶大于初始容量16, 阈值左移1(扩大为原有的2倍)   
                newThr = oldThr << 1; // double threshold
        }
        // 下面情况是数组容量小于等于0,说明数组还未被初始化
        
        else if (oldThr > 0) // HashMap构造函数中传入了指定容量,使用指定容量初始化数组
            newCap = oldThr;
        else {               // oldThr小于等于0,数组使用默认容量初始化数组
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        
        /* ② 创建新的数组,更新 threshold 和 数组 **/
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @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) // 如果为树节点,切割树节点,这时如果树的大小小于等于6就会被转成链表
                        ((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;
    }
① 计算扩容后的容量和阈值
  1. HashMap已经初始化(数组容量大于0)
    table的容量以及threshold量扩大为原有的两倍。 newCap = oldCap * 2 newThr = oldThr * 2

  2. 指定容量的构造方法初始化HashMap(oldThr > 0)

    //指定容量和加载因子构造函数
    public HashMap(int initialCapacity, float loadFactor) {
        ... ...
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
    //取容量最接近2的次幂 的值,为阈值    
    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;
    }
    
    newCap = threshold
    newThr = newCap * loadFactor
    
  3. 默认构造方法初始化HashMap(oldThr = 0)

    newCap = DEFAULT_INITIAL_CAPACITY = 16
    newThr = DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR = 12
    
② 创建新数组

Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

② 迁移数据至数组
  1. 节点无子节点
    直接重新计算该节点的index
    newTab[e.hash & (newCap - 1)] = e;
    
  2. 节点为链表
    因为HashMap的容量为2的倍数,扩容后也是扩容一倍,所以不用重新计算index,
    只需要判断 x = (e.hash & oldCap)
    
    x == 0 :说明 e 节点的hash值小于 oldCap,那么这些节点的 newIndex = oldIndex。
    
    x != 0 :说明 e 节点的hash值大于等于 oldCap,那么这些节点的 newIndex = (oldIndex + oldCap)
    
  3. 节点为红黑树
    和链表迁移方式相同,多了一步判断红黑树大小如果小于等于6的话会转换为链表结构
    

扩展

HashMap的大小为什么必须是2的倍数?
1.计算数组index时,2的倍数会减少Hash冲突
# index 的算法,n 表示 HashMap 的容量

index = (n - 1) & hash 
n 为2的倍数
进制n = 8(n-1) = 7hash = 10
二进制0000 10000000 01110000 1010
# 计算hash为 10,11,12 的index

(n-1) & 10 = 0000 0010 = 2
(n-1) & 11 = 0000 0011 = 3
(n-1) & 12 = 0000 0100 = 4
n 不为2的倍数
进制n = 9(n-1) = 8hash = 10
二进制0000 10010000 10000000 1010
# 计算hash为 10,11,12 的index

(n-1) & 10 = 0000 1000 = 8
(n-1) & 11 = 0000 1000 = 8
(n-1) & 12 = 0000 1000 = 8

这里可以看出,n 如果是2的倍数,n-1 则会将后置位的0全部变为1,如果 n 不为2的倍数,则 n-1 的后置位可能存在0,那么无论 hash 值的二进制位为 1 还是 0,&计算后的结果都为0,所以会增加hash冲突

2.每次扩容都是扩容一倍,所以扩容后的大小也是2的倍数,将已经产生hash碰撞的元素转移到新的table中时不用去重新计算index

假设:

oldCap = 8oldCap-1newCap == 16newCap-1
0000 10000000 01110001 00000000 1111
如果: hash < oldCap ,那么hash值的低位第4位一定为0
所以:hash & (oldCap-1) == hash & (newCap-1)
即:newIndex = oldIndex

如果: hash >= oldCap ,那么hash值的低位第4位一定为1
所以:(hash & (oldCap-1)) + oldCap == hash & (newCap-1)
即:newIndex = (oldIndex + oldCap)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值