欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-28 13:56:34
在JDK1.8中对HashMap的底层实现做了修改。本篇对HashMap源码从核心成员变量到常用方法进行分析。 HashMap数据结构如下: 先看成员变量: 1、底层存放数据的是Node[]数组,数组初始化大小为16。 2、Node[]数组最大容量 3、负载因子0.75。也就是如 ......

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

  hashmap数据结构如下:

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

  先看成员变量:

  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(JDK1.8)

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本身线程不安全的特性并没有改变。