java多线程系列11-多线程下HashMap源码分析

Map系列文章
java多线程系列12-ConcurrentHashMap源码分析
java多线程系列13-ConcurrentSkipListMap、ConcurrentSkipListSet源码分析

1.Hashmap

hashmap低层数据结构用的是数组加链表。这时候就会涉及到几个问题,如何定位数据在hashmap中的位置?如何减少hash冲突?如何保证hash值不超过数组的长度。

1.1 hash

哈希:把任意长度的输入通过一种算法(散列),变换成为固定长度的输出,这个输出值就是散列值。属于压缩映射,容易产生哈希冲突。
产生哈希冲突时解决办法:1.开放寻址;2、再散列;3、链地址法(相同hash值的元素用链表串起来)。

  • 开放寻址:当要插入一个元素时,可以连续地检查散列表的个各项,直到找到一个空槽来放置这个元素为止。检查顺序可以是线性的,可以是二次的,也可以是再次散列的。
  • 再散列:二次再散列法是指第一次散列产生哈希地址冲突,为了解决冲突,采用另外的散列函数或者对冲突结果进行处理的方法。
  • 链地址法:hashmap采用的方法,相同hash的数据用链表连接。

1.2 jdk1.7版本的hashmap

(1)put方法

    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        //将key的hash值进行再次hash,主要是为了减少hash值的碰撞
        int hash = hash(key.hashCode());
        //将hash值与数组长度求余,防止上述hash值超出数组范围
        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;
            }
        }

        modCount++;
        //将节点加入到链表的头部
        addEntry(hash, key, value, i);
        return null;
    }

2.hash方法

    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
    	//对key的hashcode值再次计算,减少hash冲突的概率
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

3.indexFor方法

    static int indexFor(int h, int length) {
    	//为保证hash值在数据范围内,用hash值和数组长度求余
    	//如果N是2的指数幂,一个数h和N-1进行与运算就是用h和N求余
        return h & (length-1);
    }

4.hashmap在多线程下链表的死循环
hashmap的死循环是发生在扩容时。扩容核心代码如下:

    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;//步骤1
                    int i = indexFor(e.hash, newCapacity);//步骤2
                    e.next = newTable[i];//步骤3
                    newTable[i] = e;//步骤4
                    e = next;//步骤5
                } while (e != null);
            }
        }
    }

在这里插入图片描述
描述下死循环的场景:
1.现在有两个线程A和B同时执行扩容,线程A执行步骤1后被挂起,这个线程A的e为3,next为7。
2.线程B进行扩容,完成后,结果为图中第三步所示,注意此时7的next为3.
3.此时线程A被唤醒,执行步骤2,此时newTable[i]为7。
4,.线程A继续执行步骤3,将newTable[i]赋值给e.next,注意此时e为3,newTable[i]为7。那么步骤3执行完后,3的next为7。
5.结合步骤2,此时3和7的next互相指向对方,死循环。

1.3 jdk1.8版本的hashmap

(1)put方法

  public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

(2)hash方法

    static final int hash(Object key) {
        int h;
        //为解决hash冲突
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

(3)putVal方法

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //防止hash超出数组范围,也是和数组长度求余
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            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);
                        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);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

(4)1.8的扩容不会出现链表死循环,可能出现数据不一致。但是否会因为其他原因出现死循环,这个还有待分析。

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        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;
                            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);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

总结:多线程下不要使用hashmap,使用ConcurrentHashMap。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值