HashMap多线程操做写入时为什么会出现死循环?

HashMap不是线程安全的,多线程写入修改时可能出现死循环,会致使CPU迅速被占用至90%。经过源码能够看出出现死循环的缘由:数组

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        //上面是hashcode相同,key也相等时,替换掉原值,返回老值。
        //不然执行下面的操做
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

出现死循环的代码部分就从这个addEntry(hash, key, value, i)开始,分析下addEntry(hash, key, value, i)的代码:安全

void addEntry(int hash, K key, V value, int bucketIndex) {
        //新元素插入到桶的头部
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        //若是元素个数超过阈值,则扩容
        if (size++ >= threshold)
            resize(2 * table.length);
    }

当元素个数超过阈值则会扩容,扩容时会出现从新hash,下面分析这个扩容的方法resize(2 * table.length):多线程

void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        //将元素转移到newTable中
        transfer(newTable);
        table = newTable;
        threshold = (int)(newCapacity * loadFactor);
    }

继续跟进代码看这个transfer(newTable)方法的实现:并发

void transfer(Entry[] newTable) {
        Entry[] src = table;
        int newCapacity = newTable.length;
        for (int j = 0; j < src.length; j++) {
            Entry<K,V> e = src[j];
            if (e != null) {
                src[j] = null;
                do {//这个循环就是引发死循环的罪魁祸首
                    Entry<K,V> next = e.next;
                    int i = indexFor(e.hash, newCapacity);
                    e.next = newTable[i];
                    newTable[i] = e;
                    e = next;
                } while (e != null);
            }
        }
    }

下面分析这个do循环,显得有点绕,其实是一个最节省空间(没有额外分配任何空间)的一个倒序排列,即把原来Entry数组的一个Entry倒序构建新table的Entry。若是原来某个Entry里面元素排序是e1--->e2....,线程T1写入操做引起扩容倒序写入新table变成了....e2--->e1;线程T2写入操做时倒序则是e1---->e2....;如此则两个线程并发写入时可能会造成一个闭环死循环,会致使CPU迅速占用100%程序卡死。this

相关文章
相关标签/搜索