浅谈HashMap源码

  • HashMap结构(JDK 1.8)

public class HashMap extends AbstractMap
    implements Map, Cloneable, Serializable {

    //重要字段
    static class Node;
    Node[] table;
    transient int size;
    transient int modCount;
    int threshold;
    final float loadFactor;
    ...

    //重要常量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //16;Node数组的初始化长度
    static final int MAXIMUM_CAPACITY = 1 << 30;//Node数组的最大长度
    static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认加载因子的大小
    static final int TREEIFY_THRESHOLD = 8;//Node链表要多长才转为红黑树
    static final int UNTREEIFY_THRESHOLD = 6;
    static final int MIN_TREEIFY_CAPACITY = 64;


    //重要方法
    static final int hash(Object key)
    public V get(Object key)
    public V put(K key, V value)
    final Node[] resize()
    final void treeifyBin(Node[] tab, int hash)
    ...

}

重要字段

Node[] table 与 Node node
Map map = new HashMapHashMap();
map.put("name", "huangzp");
map.put("age", 23);

HashMap执行这段代码时,实际是把key和value(比如"age"和"23")封装到Node的对象里面,然后再把Node对象放到Node数组的某个位置去.

static class Node implements Map.Entry {
        //Node对象的hash值,通过hash(key)方法获得,用于确定Node对象在Node数组里面的位置index((length - 1) & hash)
        final int hash;
        final K key;
        V value;
        //当Node对象的hash值一样,即在Node数组中的位置一样,HashMap会把新的Node节点挂到原来的Node节点后面(next指向),形成一个链表,当Node链表超过8个,链表会转成红黑树
        Node next;
}

Node数组的初始化长度为16,每次扩容变成原来的两倍,即2的n次方

int size

HashMap里面的元素总个数.

int modCount

hashmap被修改的次数
fast-fail hashMap初始化迭代器的时候会把当前的modCount值记下来,然后每次迭代都会把记下来的modCount值和当前的modCount值做比较,如果迭代过程有其他线程修改了map,即改变了modCount的值,那么将抛出ConcurrentModificationException

float loadFactor 与 int threshold

loadFactor 负载因子(默认值是0.75)
threshold HashMap的阈值,threshold = table.length * loadFactor,当size > threshold时,HashMap会resize(扩容,把table的长度扩大一倍)

重要方法

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

hash(key)得到Node的hash值,再通过(length - 1) & hash用于确定Node对象在Node数组里面的位置

public V put(K key, V value)
    /**
     * 将key 和value关联存储起来,如果key已有其他value关联,则原来的value会被覆盖
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    /**
     * Hash是怎么储存key和value的
     */
   final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node p; int n, i;
        //如果Node数组为空,即第一次put,会初始化Node数组
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //通过(n - 1) & hash计算出key对应的Node数组的下标,找到对应的Node,如果该Node为空,创建一个新Node
        //n是Node数组的长度,它是2的n次方, n -1 转成2进制是 000..1111.. 这种形式,用 n -1 和 hash 做与运算,保证算出来的下标不会大于n
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //如果刚好Node数组对应的位置已经有Node了, e -- > 我们需要操作的那个节点; p --> 链表上的节点
            Node e; K k;
           //key一样的情况下
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果是红黑树节点
            else if (p instanceof TreeNode)
                e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
            //key不一样的情况下
            else {
                //遍历Node链表
                for (int binCount = 0; ; ++binCount) {
                    //如果Node的next为空,即链表上该节点后面没有其他Node了
                    if ((e = p.next) == null) {
                        //创建新的node
                        p.next = newNode(hash, key, value, null);
                        //当链表元素已经达到7个,加上这个等于8个,链表会转成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果已经存在Node的key为key的节点了
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //转到下一个Node节点
                    p = e;
                }
            }
            //如果e不为空,即已经存在key一样的Node了
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //把原来的值覆盖
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //modCount自增
        ++modCount;
        //如果map的大小已经超过HashMap的阈值了,node数组变为原来的两倍,并且对原来的Node节点进行重新分配
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
public V get(Object key)
    /**
     * 根据key值获取Node节点
     */
    public V get(Object key) {
        Node e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    /**
     * 如何实现
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node getNode(int hash, Object key) {
        Node[] tab; Node first, e; int n; K k;
        //计算出来的下标在Node数组里面的节点不为空
        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)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 Node[] resize() JDK 1.7

这里先来分析 1.7, JDK1.7是Entry[]数组而不是Node[]数组,实际上他们都差不多

void resize(int newCapacity) {   
     //如果Entry[]数组已经达到了最大长度,则无法扩容了
      Entry[] oldTable = table;    
      int oldCapacity = oldTable.length;         
     if (oldCapacity == MAXIMUM_CAPACITY) {  
         //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
          threshold = Integer.MAX_VALUE; 
          return;
     }
     //初始化一个新的Entry数组
      Entry[] newTable = new Entry[newCapacity];  
      //!!将数据转移到新的Entry数组里
     transfer(newTable);        
    //HashMap的table属性引用新的Entry数组                
     table = newTable;           
      //修改阈值                
     threshold = (int)(newCapacity * loadFactor);
 }
 void transfer(Entry[] newTable) {
      Entry[] src = table;                 
      int newCapacity = newTable.length;
       //遍历旧的Entry数组
      for (int j = 0; j < src.length; j++) {
          //取得旧Entry数组的每个元素
          Entry e = src[j];             
          if (e != null) {
              src[j] = null;
              do {
                  Entry next = e.next;
                 //重新计算每个元素在数组中的位置
                 int i = indexFor(e.hash, newCapacity);
                //实际上就是把e插入到 newTable[i]中, e的next指向原来的newTable[i]
                 e.next = newTable[i];
                 newTable[i] = e;      
                 e = next;          
             } while (e != null);
         }
     }
 }

为什么说HashMap是线程不安全的

在JDK1.7中,在高并发的情况下,resize之后的Entry链表可能出现死循环的情况.

  do {
        ① Entry next = e.next; 
        ② int i = indexFor(e.hash, newCapacity);
        ③ e.next = newTable[i]; 
        ④ newTable[i] = e;      
        ⑤ e = next;          
 } while (e != null);

假设现有A,B两个线程,A线程执行完第①步后因线程调度被挂起,B线程继续执行,并且执行完毕.执行后的图如下(注意A,B线程操作的都是同一个Node链表)


线程不安全

又轮到A线程执行了,A执行完第一轮的①②③④⑤以后,其示意图如下,最大的变化为newTable[3] = Entry[key = 3](表示key = 3的Entry),这时 e = Entry[key = 7]


线程不安全

然后执行第二轮①②③④⑤,第二轮执行完的变化是Entry[key = 7]被插到了newTable[3] 和Entry[key = 3]之间,这时 e = Entry[key = 3]


线程不安全

转眼间来到了第三轮,这时 e = Entry[key = 3], next = null,意味着这轮执行完这个链表就不会执行了.Entry[key = 3].next = newTable[3] ,即把Entry[key = 3]执向了Entry[key = 7],newTable[3] = Entry[key = 3],把newTable[3]指向了Entry[key = 3]至此,闭环产生,当我们再map.get(11)的时候,就会进入无限的循环
线程不安全
final Node[] resize() JDK 1.8

我们再来看JDK1.8的resize(),在1.8中,扩容每次都是 length * 2 ,,而我们的index = hash & (oldCap- 1),扩容后 index = hash & (2*oldCap - 1) = hash & ((oldCap - 1) + oldCap),
oldCap - 1 大概是 000..111这种模式,而(oldCap - 1) + oldCap相比之下多了个1,也就是说相同hash的Node节点,扩容后重新分配的节点,index要么不变,要么多了一个oldCap的距离

//index的Node链表,head只用一次,用来保存第一个Node的信息
 Node loHead = null, loTail = null;
//多了一个oldCap的index的Node链表
 Node hiHead = null, hiTail = null;
Node next;
do {
      //e就是我们旧链表的开始节点,对链表进行遍历
      next = e.next;
      // 原索引
      if ((e.hash & oldCap) == 0) {
           if (loTail == null)
                  loHead = e;
            else
                 loTail.next = e;
            loTail = e;
       }
       // 原索引+oldCap
       else {
             if (hiTail == null)
                   hiHead = e;
             else
                  hiTail.next = e;
              hiTail = e;
      }
 } while ((e = next) != null);
       // 原索引放到bucket里
        if (loTail != null) {
               loTail.next = null;
               newTab[j] = loHead;
        }
         // 原索引+oldCap放到bucket里
        if (hiTail != null) {
              hiTail.next = null;
               newTab[j + oldCap] = hiHead;
      }
 }

你可能感兴趣的:(浅谈HashMap源码)