详解Java中HashMap的实现原理

HashMap的设计简述

JDK1.8中的HashMap由数组+链表+红黑树构成,通过hash函数求下标值往数组里插入,当发生冲突时使用拉链解决,当拉链长度小于8时,使用链表;当拉链长度大于8时,使用红黑树来加快查询速度。

HashMap的源码解读

我们首先来看一下HashMap的几个重要字段:

  • table:用来存放数据,每一个元素都是一个Node键值对,初始容量为16
  • size:table中实际包含的Node数量
  • loadFactor:负载因子,默认为0.75,这是对空间和时间的一种trade off的选择,不建议大家随便修改。当负载因子调低时,使用的空间更多,但发生碰撞的几率更低,因此时间效率更佳;当负载因子调高时,使用的空间更少,但发生碰撞的几率更高,因此空间效率更佳。
  • threshold:threshold = table.length() * loadFactor,当size == threshold时,需要对table进行扩容
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    ...
    // 位桶数组
    transient Node<K,V>[] table;
    // 位桶数组table中实际包含的键值对数量
    transient int size;
    // 需要resize位桶数组的阈值
    int threshold;
    // 负载因子:默认0.75
    final float loadFactor;
    // 默认初始容量:16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    ...
}

接下来我们对HashMap的几个重要方法的源码进行探索。

首先来看一看hash方法,其调用了对象的hashCode方法,然后把hash值的高16位和低16位进行异或:

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

下面看put方法的源码:

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

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

其内部逻辑可用如下流程图表示:


  • 判断键值对数组 table是否为空或为 null,若为空则执行 resize()进行扩容;
  • 根据键值 key 计算 hash 值得到插入的数组索引 i,如果 table[i]==null,直接新建节点添加,方法结束;
  • 当 table[i]不为空,判断 table[i]的首个元素是否和传入的 key 一样,如果相同直接覆盖 value;
  • 判断 table[i] 是否为 treeNode,即 table如果是红黑树,则直接在树中插入键值对;
  • 遍历 table[i],判断链表长度是否大于 8,大于 8 的话把链表转换为红黑树,在红黑树中执行插入操作;遍历过程中若发现 key 已经存在直接覆盖 value ;若不存在则在链表尾部插入新节点;
  • 插入成功后,判断实际存在的键值对数量 size 是否超多了最大容量 threshold,如果超过,进行扩容操作;

关于红黑树的建立及插入等方法比较复杂,这里就不细讲了。接下来看一下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;
        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;
        @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;
    }

其内部逻辑可用如下流程图表示:


  • 计算新的阈值,新的阈值是旧阈值的两倍,并初始化新的数组
  • 将旧数组转移到新数组
  • 返回新数组

下面看一下get方法的源码:

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            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);
            }
        }
        return null;
    }

其内部逻辑如下图所示:


  • 首先通过 hash()函数得到对应数组下标。
  • 判断第一个元素与 key 是否匹配,如果匹配就返回参数值;
  • 判断如果是红黑树结构,就进入红黑树查找;
  • 如果不是红黑树结构,就直接遍历查找;
  • 若查找不到,则返回null。

以上所述方法是HashMap的核心,其它方法都基于以上方法完成或者大同小异,读者可自行阅码。

HashMap与并发安全

JDK1.7中,HashMap在并发的情况下发生resize时,由于使用了头插法对元素进行rehash,导致可能会产生循环链表,在执行get的时候,会触发死循环,引起CPU的100%问题,所以一定要避免在并发环境下使用HashMap。

注意,JDK1.8中对此问题进行了优化,转移元素时采用尾插法,理论上已经解决了该问题,但有网友测试发现在其他地方也会造成死循环,因此,还是切记莫要再并发环境下使用HashMap。


每日学习笔记,写于2020-05-04 星期一

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容