美文网首页
HashMap源码解读

HashMap源码解读

作者: 在一颗大大大榕树下 | 来源:发表于2019-03-26 17:37 被阅读0次
1. 数据结构

在Java中,是通过数组和链表这俩种数据结构来进行数据存储的。

  • 数组:
  1. 数组的存储空间的连续的,所以占内存严重
  2. 二分查找复杂度小
  3. 寻址容易,插入删除难
  • 链表:
  1. 区间离散,占用内存比较宽松
  2. 空间复杂度很小,时间复杂度很大
  3. 寻址难,插入删除容易

哈希表(Hash Table)就是这两者的结合,插入删除简单,寻址容易,占用内存相对宽松。

  • 拉链法(链地址法):链表的数组
拉链法

最常用的哈希表排列法,一目了然的数组+链表组合。
存储规则:整个数组长度为16,每个元素存储的是一个链表的头结点。比如:1%16 = 1,337%16 = 1,353%16 = 1 。余数皆为1,所以这三个元素被存储在数组下标为1的位置。

解决哈希冲突:同数组下标下,通过链式结构避免索引值冲突。

而HashMap就是典型的拉链法哈希表结构。

他实际上是一个线性数组。他的静态内部类继承了一个Entry接口。这里注意,在jdk1.8中,在链表中加入了红黑树(平衡二分查找树)。所以1.8版本的HashMap是由数组+(链表+红黑树)实现的。

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
    ......
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//hash code value for this map entry
        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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
    ......
}

乍一眼就能看出是一个bean类,关键的参数有三个:key,value,next,接下来我们看下HashMap的方法与Entry的关联

  1. get方法
public V get(Object key) {
   Node<K,V> e;
   return (e = getNode(hash(key), key)) == null ? null : e.value;//key是否存在,存在返回key的value值,不存在返回null
  //hash(key)获得key的hash值
}

getNode方法


    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; //Entry数组
        Node<K,V> first, e; 
        int n; //数组长度
        K k;
        // 1. 定位键值对所在桶的位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //2.判断键值的hashcode相等,对象相等
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                // 3..如果 first 是 TreeNode 类型,则调用黑红树查找方法
                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;
    }
  1. 我们看一下判断条件。前两个是tab非空判断,没什么好说的,看下第三个条件。
    (first = tab[(n - 1) & hash]) != null其中

    tab[(n - 1) & hash]这个可能有点难理解。这里是为了运算出桶在桶数组中的位置。HashMap 中桶数组的大小 length 总是2的幂,此时,(n - 1) & hash 等价于对 length 取余。
    随便假设一对值,比如hash = 98n = 2198 & (21-1) = 0,是不是和下方图示运算结果一样?位运算效率是高于运算符的,这算是java优化中的小细节。

位运算取余数
  1. 这里需注意,hashcode相同不代表是同一个对象,只有equals才能判断两个是否是同一对象(键值)
  1. 黑红树是jdk1.8在HashMap的性能优化中新添加的特性。它主要有五大性质:
  • 节点是红色或黑色。
  • 根是黑色。
  • 所有叶子都是黑色(叶子是NIL节点)。
  • 每个红色节点必须有两个黑色的子节点。(从每个叶子到根的所有路径上不能有两个连续的红色节点。)
  • 从任一节点到其每个叶子的所有简单路径都包含相同数目的黑色节点(简称黑高)。
红黑树
  1. put方法
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);//1. onlyIfAbsent参数
    }
/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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
        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;
            // 如果键的值以及节点 hash 等于链表中的第一个键值对节点时,则将 e 指向该键值对
            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);
                        //链表长度超过或等于树化阙值(8),对链表进行树化
                        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)//1.onlyIfAbsent 判断
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  1. onlyIfAbsent这个参数,牵扯到另外一个put方法:putIfAbsent方法
  public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
  }

他和put方法唯一的区别就是onlyIfAbsent的值为true

特点:putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值。
如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,返回null

  1. resize方法

resize(),咱们称之为扩容方法,只有在两种情况下会被调用:

  • HashMap实行了懒加载: 新建HashMap时不会对table进行赋值, 而是到第一次插入时, 进行resize时构建table;
  • 当HashMap的size值大于 threshold时, 会进行resize(); 看一下threshold在源码中的注解:
// (The javadoc description is true upon serialization.
   // Additionally, if the table array has not been allocated, this
   // field holds the initial array capacity, or zero signifying
   // DEFAULT_INITIAL_CAPACITY.)
   int threshold;

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

1 << 4是位运算,结果threshold默认值为16。

resize()方法源码:

   /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */

     final Node<K,V>[] resize() {

        Node<K,V>[] oldTab = table;//将当前table暂存到oldtab来操作

        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;//阈值设置为Integer的最大值,好像是2147483647,远大于默认的最大容量

                return oldTab;//直接返回当前table,不用扩容

            }

            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&

                     oldCap >= DEFAULT_INITIAL_CAPACITY)

                newThr = oldThr << 1; // 双倍扩大老内存和老阈值并赋给新的table

        }

        else if (oldThr > 0) // initial capacity was placed in threshold

            newCap = oldThr;

        else {               //这种情况是初始化HashMap时啥参数都没加

            newCap = DEFAULT_INITIAL_CAPACITY;

            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

        }

        if (newThr == 0) {//当只满足老阈值大于0的条件时,新阈值等于新容量*默认扩容因子

            float ft = (float)newCap * loadFactor;

            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?

                      (int)ft : Integer.MAX_VALUE);

        }

        threshold = newThr;//把新的阈值赋给当前table

        @SuppressWarnings({"rawtypes","unchecked"})

            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//创建容量为newCap的新table

        table = newTab;

        if (oldTab != null) {

            for (int j = 0; j < oldCap; ++j) {//对老table进行遍历

                Node<K,V> e;

                if ((e = oldTab[j]) != null) {//遍历到的赋给e进行暂存,同时将老table对应项赋值为null

                    oldTab[j] = null;

                    if (e.next == null)//将不为空的元素复制到新table中

                        newTab[e.hash & (newCap - 1)] = e;//等于是创建一个新的空table然后重新进行元素的put,这里的table长度是原table的两倍

                    else if (e instanceof TreeNode)//暂时没了解红黑树

                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

                    else { // preserve order

                        Node<K,V> loHead = null, loTail = null;//用于保存put后不移位的链表

                        Node<K,V> hiHead = null, hiTail = null;//用于保存put后移位的链表

                        Node<K,V> next;

                        do {

                            next = e.next;

                            if ((e.hash & oldCap) == 0) {//如果与的结果为0,表示不移位,将桶中的头结点添加到lohead和lotail中,往后如果桶中还有不移位的结点,就向tail继续添加

                                if (loTail == null)//在后面遍历lohead和lotail保存到table中时,lohead用于保存头结点的位置,lotail用于判断是否到了末尾

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

4.线程安全
HashMap是线程不安全的,但是HashTable由于每次put操作就进行锁死效率十分低下。那有没有既效率又线程安全的HashMap呢?

答案就是:ConcurrentHashMap

  • 底层采用分段的数组+链表实现,线程安全
  • 通过把整个Map分为N个Segment,可以提供相同的线程安全,但是效率提升N倍,默认提升16倍。(读操作不加锁,由于HashEntry的value变量是 volatile的,也能保证读取到最新的值。)
  • Hashtable的synchronized是针对整张Hash表的,即每次锁住整张表让线程独占,ConcurrentHashMap允许多个修改操作并发进行,其关键在于使用了锁分离技术
  • 有些方法需要跨段,比如size()和containsValue(),它们可能需要锁定整个表而而不仅仅是某个段,这需要按顺序锁定所有段,操作完毕后,又按顺序释放所有段的锁
  • 扩容:段内扩容(段内元素超过该段对应Entry数组长度的75%触发扩容,不会对整个Map进行扩容),插入前检测需不需要扩容,有效避免无效扩容

参考:https://www.cnblogs.com/heyonggang/p/9112731.html

相关文章

网友评论

      本文标题:HashMap源码解读

      本文链接:https://www.haomeiwen.com/subject/cxvgvqtx.html