Hashmap在JDK8中的提升

HashMap使用key的hashCode()和equals()方法来将值划分到不同的桶里。

桶的数量通常要比map中的记录的数量要稍大。这样 每一个桶包含的值会比較少(最好是一个)。当通过key进行查找时,我们能够在常数时间内迅速定位到某个桶(使用hashCode()对桶的数量进行取模) 以及要找的对象。

这些东西你应该都已经知道了。你可能还知道哈希碰撞会对hashMap的性能带来灾难性的影响。假设多个hashCode()的值落到同一个桶内的 时候,这些值是存储到一个链表中的。最坏的情况下,全部的key都映射到同一个桶中,这样hashmap就退化成了一个链表——查找时间从O(1)到 O(n)。

当然这是在jdk8曾经,JDK1.6中HashMap採用的是位桶+链表的方式,即我们常说的散列链表的方式,而JDK1.8中採用的是位桶+链表/红黑树的方式。也是非线程安全的。当某个位桶的链表的长度达到某个阀值的时候,这个链表就将转换成红黑树。

看以下的代码

//链表节点
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
     //省略 
}
//红黑树节点
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);
        }
        //省略  
}
// HashMap的主要属性
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    // 槽数组。Node<K,V>类型。TreeNode extends LinkedHashMap.Entry<K,V>,所以能够存放TreeNode来实现Tree bins
    transient Node<K,V>[] table;
    
    transient Set<Map.Entry<K,V>> entrySet;

    transient int size;
    // 去掉了volatile的修饰符
    transient int modCount;

    int threshold;

    final float loadFactor;

    ...

}
//计算key的hash
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
 }
饭后我们在看看详细的put和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;
            //hash & length-1 定位数组下标
            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) {
                    /*第一个节点是TreeNode,则採用位桶+红黑树结构,
                     * 调用TreeNode.getTreeNode(hash,key),
                     *遍历红黑树。得到节点的value
                     */
                    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;
        }
     final TreeNode<K,V> getTreeNode(int h, Object k) {
             //找到红黑树的根节点并遍历红黑树
         return ((parent != null) ? root() : this).find(h, k, null);
     }
     /*
      *通过hash值的比較,递归的去遍历红黑树,这里要提的是compareableClassFor(Class k)这个函数的作用。在某些时候
      *假设红黑树节点的元素are of the same "class C implements Comparable<C>" type 
      *利用他们的compareTo()方法来比較大小,这里须要通过反射机制来check他们究竟是不是属于同一个类,是不是具有可比較性.
      */
     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;
     }



//put(K key,V value)函数 
    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;
         //假设table为空或者长度为0,则resize()
         if ((tab = table) == null || (n = tab.length) == 0)
             n = (tab = resize()).length;
         //找到key值相应的槽而且是第一个,直接增加
         if ((p = tab[i = (n - 1) & hash]) == null)
             tab[i] = newNode(hash, key, value, null);
         else {
                 Node<K,V> e;
                 K k;
                 //第一个node的hash值即为要增加元素的hash
                 if (p.hash == hash &&
                     ((k = p.key) == key || (key != null && key.equals(k)))){
                      e = p;
                 }else if (p instanceof TreeNode)//第一个节点是TreeNode,即tree-bin
                    /*Tree version of putVal.
                     *final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,int h, K k, V v)
                     */
                     e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                     else {
                         //不是TreeNode,即为链表,遍历链表
                         for (int binCount = 0; ; ++binCount) {
                             /*到达链表的尾端也没有找到key值同样的节点,
                              *则生成一个新的Node,而且推断链表的节点个数是不是到达转换成红黑树的上界
                              *达到。则转换成红黑树
                              */
                             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);
                     //返回旧的value值
                     return oldValue;
                 }
         }
         ++modCount;
         if (++size > threshold)
             resize();
         afterNodeInsertion(evict);
         return null;
}


HashMap会动态的使用一个专门的treemap实现来替换掉它。

这样做的结果会更好,是O(logn)。而不是糟糕的O(n)。

它是怎样工作 的?前面产生冲突的那些KEY相应的记录仅仅是简单的追加到一个链表后面,这些记录仅仅能通过遍历来进行查找。

可是超过这个阈值后HashMap開始将列表升 级成一个二叉树,使用哈希值作为树的分支变量,假设两个哈希值不等,但指向同一个桶的话,较大的那个会插入到右子树里

个性能提升有什么用处?例如说恶意的程序,假设它知道我们用的是哈希算法。它可能会发送大量的请求,导致产生严重的哈希碰撞。然后不停的訪问这些 key就能显著的影响server的性能。这样就形成了一次拒绝服务攻击(DoS)。

JDK 8中从O(n)到O(logn)的飞跃,能够有效地防止类似的攻击,同一时候也让HashMap性能的可预測性略微增强了一些。




转载请注明出处http://blog.csdn.net/a837199685

原文地址:https://www.cnblogs.com/yxysuanfa/p/7160283.html