HashMap 与 ConcurrentHashMap

HashMap 与 ConcurrentHashMap

HashMap

线程不安全~
HashMap在8中 的数据结构 数组+链表+红黑树

这个结构很容易理解,任何一种hash算法都无法避免hash碰撞。

  1. 未碰撞状态,肯定是以数组形式存储;
  2. 碰撞,则以链表形式存储
  3. 默认链表长度大于8,转为红黑树结构存储
  4. 红黑树长度小于6,再转回链表

红黑树可以去了解一下,类似平衡二叉树,所以查找 可以看作二分查找,二分查找速度肯定是大于链表的。

HashMap的put操作(Java8)~写了一些流程的大概注释,方便理解

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长度是否为空,或者长度为0;是:则初始化/扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            //resize()不只能初始化,也可扩容
            n = (tab = resize()).length;
        //计算hash值,判断该存储位置是否为null,为null,直接插入;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> 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<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
                            //大于8,转为红黑树
                            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;
    }

源码中明显一行代码,为++modCount(jdk7以前为modCount++),自加是一个非原子性操作,从这里就可以看出,hashMap非线程安全。

ConcurrentHashMap

线程安全的一种map集合

jdk7中,是采用分段锁的形式,如下图所示。从这点就可以看出它比hashtable优的一点就是,hashtable使用synchronized将整个集合锁住了。ConcurrentHashMap是分段锁住。

在这里插入图片描述

jdk8中,更颗粒度了,它在数组结构的插入,也就是没有hash碰撞的情况下,使用CAS插入新value;在产生hash碰撞时,链表的插入使用了synchronized锁住操作。同时它的node结构中的value使用volatile关键字修饰,保证了线程间的可见性,为CAS(乐观锁的一种,比较交换)提供了获取当前value的需求吧。源码其中截图参考如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44969687/article/details/106935500