Java源码解读(一)——HashMap的resize与put

HashMap是java面试必不可少的问题之一,这里只列出了java1.8中比较难读懂的put操作的源码,get操作的源码请自行阅读。

new

申请内存是在第一次的put操作时进行的

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) {
        // 如果大于等于2^30,直接返回旧的map
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 如果oldCap翻倍还在2~2^30之内,newCap和newThr翻倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    // 如果oldCap==0但是oldThr已被赋值
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    // 如果oldCap与oldThr都没被赋值,也就是创建对象的时候调用的是无参构造函数
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 如果newThr还没被赋值
    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) {
    	// 用e遍历oldTab,重新赋值
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // 如果一个bucket只有一个节点,直接把引用移过来,注意rehash了
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                // 如果是红黑树
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                // 如果不止一个节点,但还没达到变为红黑树的节点数(8)
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    // 举例子,olCap=16,put使用的是oldCap-1=15
                    // 0&15=0, 16&15=0, 32&15=0, 48&15=0
                    do {
                        next = e.next;
                        // 0&16=0, 32&16=0,这两个存到loHead链表
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        // 16&16=16, 48&16=16,这两个存到hiHead链表
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    // 将两个链表放入newTab的bucket里面去
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

put

putVal
// 添加成功则返回null,否则表示更新该key,返回旧value
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // HashMap在第一次put的时候才会申请内存
    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;
        // 已存在k,赋值给e
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 如果p是TreeNode,用putTreeVal插入;已存在则返回k,v对,添加成功则返回null
        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);
                    // 链表大于8,变为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 已存在k,跳出
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // e为null表示添加成功,不为null表示已存在;已存在则更新value,返回旧value
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 大于阈值,则扩容,默认为16*0.75
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
putTreeVal
// 已存在则返回节点,添加成功则返回null;更新操作不在这里
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    TreeNode<K,V> root = (parent != null) ? root() : this;
    // 用p从root开始遍历
    for (TreeNode<K,V> p = root;;) {
        int dir, ph; K pk;
        // p.hash大于h
        if ((ph = p.hash) > h)
            dir = -1;
        // p.hash小于h
        else if (ph < h)
            dir = 1;
        // 已存在,直接返回该节点,更新操作不在这里
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        // k.class为空 || p.k.class为空 || p.key.class不等于k.class
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) {
            // 没找到
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                // 从左右子树中找到,则返回;否则返回null
                if (((ch = p.left) != null &&
                     (q = ch.find(h, k, kc)) != null) ||
                    ((ch = p.right) != null &&
                     (q = ch.find(h, k, kc)) != null))
                    return q;
            }
            // 用native方法来识别p.key.class是否与k.class一致
            dir = tieBreakOrder(k, pk);
        }

        TreeNode<K,V> xp = p;
        // 遍历p,当p为空时,添加节点
        if ((p = (dir <= 0) ? p.left : p.right) == null) {
            Node<K,V> xpn = xp.next;
            TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
            if (dir <= 0)
                xp.left = x;
            else
                xp.right = x;
            xp.next = x;
            x.parent = x.prev = xp;
            if (xpn != null)
                ((TreeNode<K,V>)xpn).prev = x;
            moveRootToFront(tab, balanceInsertion(root, x));
            return null;
        }
    }
}

remove

removeNode
// 正确移除该值,返回node;没找到,返回null
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    // 如果当前bucket有值
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        // 找到要remove的值,赋给node
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        // 如果找到要remove的值,移除它
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

扩展

上面只解读了java1.8中的源码,但是一些细节性的因素并没有提及,比如

  1. HashMap默认的初始长度是多少?为什么这么规定?
  2. 高并发情况下,HashMap会出现死锁吗?
  3. Java8中,HashMap有怎样的优化?

下面的这篇博客解释了一些原因:
https://blog.csdn.net/mbshqqb/article/details/79799009

你可能感兴趣的:(源码解读)