HashMap的线程不安全分析

大家都知道hashMap是线程不安全的,concurrentHashMap是线程安全的,而具体的原因可能还不是很清楚。

现在先来分析一下hashMap的代码:(jdk 1.8)

几个基础数据:

     int threshold;             // 所能容纳的key-value对极限 
     final float loadFactor;    // 负载因子,默认值为0.75
     int modCount;     //map结构修改的次数
     int size;           //HashMap中实际存在的键值对数量
     Node<K,V>[] table;  // 存放链表的数组

Node[] table的初始化长度length(默认值是16),threshold = length * Load factor。threshold就是当前loadFactor和length对应下允许的最大元素数目,超过这个数目就重新resize。

jdk在到1.8的时候多了很多新特性,hashmap也做了很多改动,由之前的数组+链表的模式,变成了数组+链表或数组+红黑树的模式。原因可想而知,当hash冲突增多的时候,长长的链表挂在一个数组节点上,这时候的get操作就变成了单一的O(n)链表搜索。用红黑树的模式可以增加搜索的效率。

     /**
     * 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;

    注释里写的很清楚,添加了TREEIFY_THRESHOLD作为默认的采用树结构的阈值,长度>2且至少为8。当长度大于阈值的时候,链表结构会转成红黑树。而当元素删除,长度小于阈值时,红黑树结构又会变回链表结构。

新的hashMap,所有的节点类型是Node,里面定义了一些基本方法:

 /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    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;
        }

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

接下来是比较重要的put方法,真正的实现放在putVal中:

整体分为三个步骤:

1、如果当前的table为null或长度为0,重新扩展该数组。
2、如果在数组中根据hash找到的位置为null,都没有头节点,需要先生成一个头节点
3、之后的判断都是找目标节点,找到赋给e跳出,没找到就new一个放在合适的位置,不赋值。(1.8多了对树的类型判断) 

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 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为null或长度为0,重新扩展该数组。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果在数组中根据hash找到的位置为null,都没有头节点,需要先生成一个头节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //下面的判断都是找目标节点,找到赋给e跳出,没找到就new一个放在合适的位置,不赋值。(1.8多了对树的类型判断)
            //因为key是对象型,可能是值的引用类型,例如Integer,所以可以尝试先用‘==’直接比较值;也有可能是对象引用类型,所以需要equals来二次判断
            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) {
                    //到最后也没找到key相同的,在末尾插入节点    
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果当前插入节点后链表长度> TREEIFY_THRESHOLD,变成树结构
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //找到了key相同的节点
                    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;
    }
                       

  看下判断key值相等的条件:
            if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))   

因为key是对象型:

 1、有可能是null,那么‘null==null’可以判断为true。(所以HashMap的key和value都可以为null。null在hash()被处理放在0的位置)

 2、可能是值的引用类型,例如Integer,所以可以尝试先用‘==’直接比较值;

 3、也有可能是对象引用类型,所以需要equals来二次判断。

备注:hashSet的add方法就是复用了hashMap的putVal()方法,key是add的参数,value是new的Object。也就是说hashSet只用了key的部分。

然后是get方法:寻找key相同的节点。

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 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; Node<K,V> first, e; int n; K k;
        //先判断数组是不是null,长度是否大于0,当前key的hash值对应的位置是不是有链表。
        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;
    }

这里提一下hash算法,为什么不直接用key的hashCode,非要再计算一遍呢。

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

    看到这个16应该能猜得到,因为hashCode()的值是32位,把得到值和右移16位后的值进行异或操作,就是为了让高低位都能参与到hash的散列。因为大部分情况下,数组的长度size都不会那么的长,只用hashCode()的值和(size-1)做&操作,高位就被抛弃,不参与位计算。

问题就出在对数组重新调整的时候:

 /**
     * 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;
        //阈值随着容量capacity而变
        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;
                            //如果hash和之前的数组的长度oldCap做“&”操作为0,
                            //代表其之前就是挂在老数组上的,相对新数组位置的没有变。
                            //否则需要移到新数组对应的的高位(因为数组长度都是两倍的扩展)
                            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);
                        //尾节点断掉,指向null
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //高位的链表放到新的位置(2倍的位置)
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

   resize的过程本质上是把一个链表拆分成两个链表的过程,一个low,一个high,low继续保持在原来的位置,而high位的则已到2倍的位置,因为扩张都是两倍的扩。

  所以在多线程的情况下,链表极其容易发生连接的错乱,形成环形结构,或者取到了错误的值(1.7)。

  线程死锁的条件是被操作hashMap是一个静态变量,在常量区只保存一份,而在resize的过程中,新建的newTable则是线程独享的,有多个。下面我们假设没有涉及到树形结构,且简单的根据mod的值来确定数组中的位置:

1.一开始的时候,:

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

2.然后线程2继续往下走,线程1停在步骤1中所示的位置。线程2完成了低位,高位的拆分:

3.然后线程2醒了,开始第一个循环的操作:

4.高位的指针连续向后移动:

5.最终的状态:

 此时节点5没有节点的next指向它,此时若有get5的操作则不会取到相应的值,会造成数据的丢失。但是对jdk1.7中的环形结构,jdk1.8不会再出现,因为1.8的模式是先用高低位指针标记,拆分成高低位两个链表,然后分别挂在各自的位置。不会像1.7中的,一个一个节点去挂在新的位置。

但是,jdk8会出现树的死循环。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值