南风知我不易

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JDK8HashMap

文中提及HashMap7的参见博客https://www.cnblogs.com/danzZ/p/14075147.html

红黑树、TreeMap分析详见https://www.cnblogs.com/danzZ/p/14068984.html

成员变量

//同jdk7
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树化阈值,也就是说链表长度超过8才会进行树化
static final int TREEIFY_THRESHOLD = 8;
//链表化阈值,也就是说红黑树的节点个数少于6才会退化成链表
static final int UNTREEIFY_THRESHOLD = 6;
//最小树化容量,也就是说链表长度超过64才会树化
static final int MIN_TREEIFY_CAPACITY = 64;
//还是熟悉的味道,Node数组,数组加链表的存储结构
transient Node<K,V>[] table;

为什么突然多了一个树化阈值?红黑树?为什么要引入红黑树?

为什么树化阈值和链表化阈值不相等呢?

简单来说,树化阈值和链表化阈值应该相等,统一为一个阈值,超过则树化,低于则链表化,假设就规定为8,就会出现这样的问题,如果一个链表长度从7到8了,那么就树化,但是过一会儿又从8到7了,又需要变回链表,而无论链表转化成树还是树转化成链表,都是非常费时的,这就大大降低了HashMap的效率,此外在树化、链表化的过程中有大量的垃圾对象产生,从而加快触发GC

为什么树化阈值要设置为8呢?

等下揭晓

内部类Node

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

等同于JDK7的entry节点换了个名字,还是熟悉的链表

内部类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);
        }
    
}

boolean red,红黑树它来了

为什么需要红黑树?为什么是红黑树?

HashMap向外提供的功能就是时间复杂度为O(1)的查询,但是基于数组链表的冲突解决方式,以及HashMap通过位运算计算index的方式,如果hashCode的实现不能实现很好的分散效果,比如自己的类中重写了hashCode方法,可能导致某一个链表过长,从而使得HashMap的查询速度退化到O(n),这是没有办法接收的,所以需要选择一种支持快速查找的结构--有序的二叉树

为什么是红黑树

这一点在关于TreeMap中已经分析清楚了,如果选择二叉搜索树,在一定的情况下,二叉搜索树会退化成链表,而AVL树的实现复杂,插入删除效率不及红黑树,所以选择综合性能不错的红黑树。

构造方法

JDK8

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
    	//tableSizeFor方法返回一个大于initialCapacity的最小二次幂
        this.threshold = tableSizeFor(initialCapacity);
    }

JDK7

public HashMap(int initialCapacity, float loadFactor) {
    	//做一些范围检查
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
		//对loadFactor赋值以及threshold赋值
        this.loadFactor = loadFactor;
        threshold = initialCapacity;
    	//空方法,交由子类实现,在HashMap中无用
        init();
}

区别:

  • 计算大于传入capacity的第一个二次幂在JDK8的实现中,在构造函数中就完成了,并且赋值给了threshold,而在JDK7的实现中,第一次put元素的时候完成计算
  • JDK7中调用了Integer的highestOneBit()、countBit()方法计算二次幂,JDK8中自己实现了

put()详解

put()

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

新增两个参数:

@param onlyIfAbsent if true, don't change existing value 对应第四个参数-false
    如果为true,插入已经存在key时,不修改value
@param evict if false, the table is in creation mode. 对应第五个参数-true
    暂且不明

putVal()

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;
    	//(n - 1) & hash
    	//JDK8中没有了indexFor方法,但是还是采用同样的逻辑计算index
    	//为null直接插入
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //发生哈希冲突
            Node<K,V> e; K k;
            //如果与第一个node的key的hash值相同,并且key相同
            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 {
                //区别于JDK7中的头插法,采用了尾插法,为什么采用尾插法呢?
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果当前的链表长度超过了树化阈值则树化,-1是因为第一个结点没计数
                        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;
                //根据传入的参数onlyIfAbSent决定是否修改已经存在的key对应的value值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
    	//如果size超过阈值,则扩容
        if (++size > threshold)
            resize();
    	//hashMap中为空方法
        afterNodeInsertion(evict);
        return null;
}

从上面的代码可以看出数组链表的逻辑基本类似,但是JDK8中的实现中新结点的插入采用了尾插法

为什么采用尾插法呢?头插法貌似看起来更加高效

头插法的问题明天再补!

hash()

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

相较于JDK7的多次扰动,JDK8的扰动次数减少了但是利用了高16位和低16位的数据来进行扰动

扩容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;
            }
            //newCap=oldCap << 1扩容为原来的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
    	//oldCap==0
        else if (oldThr > 0) // initial capacity was placed in threshold
            //如果构造函数中计算出来的threshold被赋值给newCap了
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //如果调用了默认的构造函数,cap和threshold就会不一样
            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 { 
                        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);
                        //这里就可以直接将两条链的头部拷贝到新的node数组的相应位置即可
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

抛开红黑树来看,这里利用了一个特性

假设hashcode= 0010 1111 初始容量为8
index=hashcode&(leng-1)=0010 1111 & 0000 0111 = 0000 0111 =7
此外还有一个hashcode2 = 0000 0111
按照相同的index计算方法,两者发生了冲突,此时如果发生扩容
新的容量为16-1 = 15 = 0000 1111
此时两者再去运算结果分别为:
index1 = 1111 = 15 index2 = 0111 = 7

通过上面的举例可以看出,容量左移一位之后,左移的那一位是否为1导致旧链分裂成两条新链,而这两条新链的head结点的差值就是最高位的1表示的大小(1000=8),也就是旧的容量

初始化

其中初始化也会调用到resize方法,分别走两个分支

else if (oldThr > 0) // initial capacity was placed in threshold
    //如果构造函数中计算出来的threshold被赋值给newCap了
    newCap = oldThr;
else {               // zero initial threshold signifies using defaults
    //如果调用了默认的构造函数,cap和threshold就会不一样
    newCap = DEFAULT_INITIAL_CAPACITY;
    newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}

与JDK7中的实现不大相同,第一个分支的capacity与threshold是相同的,通过简单的实验查看验证一下

public static void main(String[] args) throws NoSuchFieldException {
    HashMap<Integer, Integer> map = new HashMap<>(8);
    Class<? extends HashMap> mapClass = map.getClass();

    //threshold
    Field threshold = mapClass.getDeclaredField("threshold");
    threshold.setAccessible(true);
    try {
        Integer num = (Integer)threshold.get(map);
        System.out.println(num);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    //capacity
    try {
        map.put(1,1);
        Method capacity = map.getClass().getDeclaredMethod("capacity");
        capacity.setAccessible(true);
        Integer c = (Integer)capacity.invoke(map);
        System.out.println(c);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

两个输出都是8,而初始化如果不传入,则会发现capacity为16,threshold为12=16*0.75,这与JDK7还是略有不同的

红黑树

树化

treeifyBin()
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        //如果length<64,不进行树化,进行扩容,扩容同样可能导致链的分裂从而缩短链的长度
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        //把Node链表转换成TreeNode链表
        do {
            //replacementTreeNode把Node转成TreeNode,new一个新的出来赋值即可
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                //你可能比较差异,TreeNode结构里面没有声明next变量,但是你顺着TreeNode的继承结构会发现它实际继承了Node,自然就会有next成员变量
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}
replacementTreeNode()
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
    return new TreeNode<>(p.hash, p.key, p.value, next);
}
关键方法treeify()
final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        //root结点为null,root->x,并且将x染黑
        if (root == null) {
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph;
                K pk = p.key;
                //利用hash排序
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                //是否利用自己定义的排序规则进行排序,这里就不细究了
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    dir = tieBreakOrder(k, pk);

                TreeNode<K,V> xp = p;
                //if dir<=0 p=p.left else p=p.right
                //二分搜索隐藏在这里
               	//if p!=null 说明还没找到
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    x.parent = xp;
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    //插入平衡,与TreeMap中的红黑树实现基本一致
                    root = balanceInsertion(root, x);
                    break;
                }
            }
        }
    }
    moveRootToFront(tab, root);
}
balanceInsertion()
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                            TreeNode<K,V> x) {
    x.red = true;
    for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
        //第一个结点,直接染黑即可
        if ((xp = x.parent) == null) {
            x.red = false;
            return x;
        }
        else if (!xp.red || (xpp = xp.parent) == null)
            //root
            return root;
        //x的父亲为祖父的左孩子
        if (xp == (xppl = xpp.left)) {
            //叔叔结点为红,父亲叔叔染黑,祖父染红,祖父成为x
            if ((xppr = xpp.right) != null && xppr.red) {
                xppr.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            //叔叔结点为Nil或者黑色
            else {
                //x为父亲的右孩子,以父亲为中心左旋
                if (x == xp.right) {
                    root = rotateLeft(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                //x为左孩子,父亲染黑,祖父染红,以祖父为中心右旋
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateRight(root, xpp);
                    }
                }
            }
        }
        //对称操作
        else {
            if (xppl != null && xppl.red) {
                xppl.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {
                if (x == xp.left) {
                    root = rotateRight(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateLeft(root, xpp);
                    }
                }
            }
        }
    }
}

树的插入

putTreeVal()

不贴代码了,一样的操作,先定位再插入,最后平衡红黑树

树化的阈值为何是8

这里贴一段HashMap中的官方的注解即可

Because TreeNodes are about twice the size of regular nodes, we
use them only when bins contain enough nodes to warrant use
 (see TREEIFY_THRESHOLD). And when they become too small (due to
removal or resizing) they are converted back to plain bins.  In
usages with well-distributed user hashCodes, tree bins are
rarely used.  Ideally, under random hashCodes, the frequency of
nodes in bins follows a Poisson distribution.The first values are:
0:    0.60653066
1:    0.30326533
2:    0.07581633
3:    0.01263606
4:    0.00157952
5:    0.00015795
6:    0.00001316
7:    0.00000094
8:    0.00000006

简单翻译一下就是,treeNode的大小大约为普通Node的2倍数,比较占内存,如果使用well-distributed也就是分布合理的hashcode方法,很难用到红黑树,因为如果完全分布合理,只会触发扩容。

所以JDK的意思就是能不用红黑树就不用

under random hashCodes, the frequency of nodes in bins follows a Poisson distribution.

如果在足够random的hashcode下,每个链表的大小服从泊松分布,可以看到当链表长度为8时,可能性已经很小了,设置成8的意思就是说在足够random的hashcode方法下,尽可能的不使用红黑树,那么设置成8就足够了

你可能有问题?既然JDK要极力避免使用红黑树,为什么还要作为一种实现添加进来呢?

上面的前提是足够随机的hashcode计算,架不住有些同志的类自己重写了hashCode方法,那么就有可能导致分布不均匀,导致链表过长,如果不树化,就妄为hashMap查询时间复杂度O(1)的名号了!!

posted on 2020-12-03 20:43  南风知我不易  阅读(221)  评论(0编辑  收藏  举报