源码分析--HashMap(JDK1.8)

  在JDK1.8中对HashMap的底层实现做了修改。本篇对HashMap源码从核心成员变量到常用方法进行分析。

  HashMap数据结构如下:

 

  先看成员变量:

  1、底层存放数据的是Node<K,V>[]数组,数组初始化大小为16。

/**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

  2、Node<K,V>[]数组最大容量

/**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

  3、负载因子0.75。也就是如果默认初始化,HashMap在size = 16*0.75 = 12时,进行扩容。

/**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

  4、将链表转化为红黑数的阀值。

 /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

  5、红黑树节点转换为链表的阀值

/**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

  6、转红黑树时,table的最小长度

/**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

 

介绍一下HashMap用hash值定位数组index的过程:

//HahsMap中的静态方法
static
final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }

//定位计算
int index = (table.length - 1) & hash
  • 先得到key的hashCode值
  • 再将hashCode值与hashCode无符号右移16位的值进行按位异或运算。得到hash值
  • 将(table.length - 1) 与 hash值进行与运算。定位数组index

给一个长度为16的数组,以"TestHash"为key,进行定位的过程实例:

HashMap中Node就是放入的数据节点,代码定义为:

  static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
}

  Node节点保存key的hash值和K--V,借助next可实现链表。

 

红黑树封装为TreeNode节点:

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

 

介绍get()方法:

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;
    }
  • index定位,得到该索引上的Node节点,赋值给first
  • 对first节点进行判断,如果是要找的元素,直接返回
  • first节点的next不为空,继续找
  • 如果first节点是红黑树,调用getTreeNode()获取值。
  • 不是红黑树,只能是链表。从头遍历,找到就返回。

  上面对于红黑树取值的getTreeNode()方法,看一下红黑树的遍历做法:

final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }
  • 从do-while循环里的第一个if开始。如果当前节点的hash比传入的hash大,往p节点的左边遍历
  • 如果当前节点的hash比传入的hash小,往p节点的右边遍历
  • 如果key值相同,就找到节点了。返回
  • 左节点为空,转到右边遍历
  • 右节点为空,转到左边
  • 如果传入key实现了Comparable接口。就将传入key与p节点key进行比较,根据比较结果选择向左或向右遍历
  • 没有实现接口,直接向右遍历,找到就返回
  • 没找到,向左遍历

 

介绍put()方法:

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,初始化
  • 定位到数组index,若该位置为空,直接放
  • 如果该位置上不为空,且hash和key与传入的值相同,说明key重复,直接将该节点赋值给e,结束循环
  • 如果该index上的节点是红黑树,调用putTreeVal()方法
  • 不是红黑树,只能是链表,遍历整个链表
  • 找到最后一个节点,在这个节点后面以k--v新增一个节点。
  • 判断链表长度,binCount达到7,也就是长度达到8。转为红黑树。
  • 遍历过程中,如果找到了相同key,就跳出循环。
  • 如果e不为空,说明遍历结束后存在key重复的节点。做值覆盖
  • 扩容判断

分析红黑树插入方法putTreeVal():

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;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        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;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = 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;
                }
            }
        }
  • 查找root根节点
  • 从root节点开始遍历
  • 如果当前节点p的hash大于传入的hash值,记dir为-1,代表向左遍历。
  • 小于,记1,代表向右遍历
  • 如果key相同,直接返回
  • 如果key所属的类实现Comparable接口,或者key相等。先从p的左节点、右节点分别调用find(),找到就返回。
  • 没找到,比较p和传入的key值,结果记为dir
  • 根据dir选择向左或向右遍历
  • 依次遍历,直到为null,表示达到最后一个节点,插入新节点
  • 调整位置

 

分析HashMap扩容方法:

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;
    }
  • 通过一系列判断,确认新table的容量
  • 构造一个新容量的Node数组,赋值给table
  • 遍历旧table数组
  • 如果节点是单节点,直接定位到新数组对应的index位置下
  • 如果是红黑树,调用split方法
  • 遍历链表。
  • 如果e的hash值与老数组容量取与运算,值为0。索引位置不变
  • 如果e的hash值与老数组容量取与运算,值为1。这在新数组中索引的位置为老数组索引 + 老数组容量。
  • 链表放置

 

简要分析多线程下HashMap死循环问题:

  JDK1.7HashMap扩容时,对于链表位置变化,采用头插法进行操作。多线程下容易形成环形链表,造成死循环。

  JDK1.8时,会对于链表hash值与容量的计算结果。分成两部分,并改为插入到链表尾部。1.8以后不会再有死循环问题,只是有可能重复放置导致数据丢失。HashMap本身线程不安全的特性并没有改变。

posted @ 2019-01-21 18:28  阳光、大地和诗歌  阅读(292)  评论(0编辑  收藏  举报