ConcurrentHashMap源码解读

    xiaoxiao2022-07-02  109

    ConcurrentHashMap源码解读

    JDK1.7及之前

    锁分段技术

        HashTable容器在竞争激烈的并发环境下表现出效率低下的原因,是因为所有访问HashTable的线程都必须竞争同一把锁,那假如容器里有多把锁,每一把锁用于锁容器其中一部分数据,那么当多线程访问容器里不同数据段的数据时,线程间就不会存在锁竞争,从而可以有效的提高并发访问效率,这就是ConcurrentHashMap所使用的锁分段技术,首先将数据分成一段一段的存储,然后给每一段数据配一把锁,当一个线程占用锁访问其中一个段数据的时候,其他段的数据也能被其他线程访问。有些方法需要跨段,比如size()和containsValue(),它们可能需要锁定整个表而而不仅仅是某个段,这需要按顺序锁定所有段,操作完毕后,又按顺序释放所有段的锁。这里“按顺序”是很重要的,否则极有可能出现死锁,在ConcurrentHashMap内部,段数组是final的,并且其成员变量实际上也是final的,但是,仅仅是将数组声明为final的并不保证数组成员也是final的,这需要实现上的保证。这可以确保不会出现死锁,因为获得锁的顺序是固定的。

    ConcurrentHashMap是由Segment数组结构和HashEntry数组结构组成。Segment是一种可重入锁ReentrantLock,在ConcurrentHashMap里扮演锁的角色,HashEntry则用于存储键值对数据。一个ConcurrentHashMap里包含一个Segment数组,Segment的结构和HashMap类似,是一种数组和链表结构, 一个Segment里包含一个HashEntry数组,每个HashEntry是一个链表结构的元素, 每个Segment守护者一个HashEntry数组里的元素,当对HashEntry数组的数据进行修改时,必须首先获得它对应的Segment锁。

    ConcurrentHashMap()中主要实体类就是三个:ConcurrentHashMap(整个Hash表),Segment(桶),Node(节点),对应上面的图可以看出之间的关系

    ConcurrentHashMap采用 分段锁的机制,实现并发的更新操作,底层采用数组+链表的存储结构。 其包含两个核心静态内部类 Segment和HashEntry。

    Segment继承ReentrantLock用来充当锁的角色,每个 Segment 对象守护每个散列映射表的若干个桶。

    HashEntry 用来封装映射表的键 / 值对;

    每个桶是由若干个 HashEntry 对象链接起来的链表。

    JDK1.8

    已经抛弃了Segment分段锁机制,利用CAS+Synchronized来保证并发更新的安全,底层采用数组+链表+红黑树的存储结构。

    重要概念

    在开始之前,有些重要的概念需要介绍一下:

    table:默认为null,初始化发生在第一次插入操作,默认大小为16的数组,用来存储Node节点数据,扩容时大小总是2的幂次方。nextTable:默认为null,扩容时新生成的数组,其大小为原数组的两倍。sizeCtl:默认为0,用来控制table的初始化和扩容操作,具体应用在后续会体现出来。

    **-1 **代表table正在初始化

    **-N **表示有N-1个线程正在进行扩容操作

    其余情况: 1、如果table未初始化,表示table需要初始化的大小。

    private static final int DEFAULT_CAPACITY = 16;

     

    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {     this.sizeCtl = DEFAULT_CAPACITY;     putAll(m); }

    2、如果table初始化完成,表示table的容量,默认是table大小的0.75倍,

    private static final float LOAD_FACTOR = 0.75f;

    居然用这个公式算0.75(n - (n >>> 2))。

    Node:保存key,value及key的hash值的数据结构。 static class Node<K,V> implements Map.Entry<K,V> {     final int hash;     final K key;     volatile V val;     volatile Node<K,V> next;     Node(int hash, K key, V val, Node<K,V> next) {         this.hash = hash;         this.key = key;         this.val = val;         this.next = next;     }       …………… }

    其中value和next都用volatile修饰,保证并发的可见性。

    ForwardingNode:一个特殊的Node节点,hash值为-1,其中存储nextTable的引用。 /* ---------------- Special Nodes -------------- */ /**  * A node inserted at head of bins during transfer operations.  */ static final class ForwardingNode<K,V> extends Node<K,V> {     final Node<K,V>[] nextTable;     ForwardingNode(Node<K,V>[] tab) {         super(MOVED, null, null, null);         this.nextTable = tab;     } …………… }

    只有table发生扩容的时候,ForwardingNode才会发挥作用,作为一个占位符放在table中表示当前节点为null或则已经被移动。

    实例初始化

    实例化ConcurrentHashMap时带参数时,会根据参数调整table的大小,确保table的大小总是2的幂次方,算法如下:

     public ConcurrentHashMap(int initialCapacity) {     if (initialCapacity < 0)         throw new IllegalArgumentException();     int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?                MAXIMUM_CAPACITY :                tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));     this.sizeCtl = cap; }

     

    private static final int tableSizeFor(int c) {     int n = c - 1;     n |= n >>> 1;     n |= n >>> 2;     n |= n >>> 4;     n |= n >>> 8;     n |= n >>> 16;     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }

     

    注意,ConcurrentHashMap在构造函数中只会初始化sizeCtl值,并不会直接初始化table,而是延缓到第一次put操作。

    table初始化

    前面已经提到过,table初始化操作会延缓到第一次put行为。但是put是可以并发执行的,Doug Lea是如何实现table只初始化一次的?让我们来看看源码的实现。

    /**  * Initializes table, using the size recorded in sizeCtl.  */ private final Node<K,V>[] initTable() {     Node<K,V>[] tab; int sc;     while ((tab = table) == null || tab.length == 0) {         if ((sc = sizeCtl) < 0)             Thread.yield(); // lost initialization race; just spin         else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {             try {                 if ((tab = table) == null || tab.length == 0) {                     int n = (sc > 0) ? sc : DEFAULT_CAPACITY;                     @SuppressWarnings("unchecked")                     Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];                     table = tab = nt;                     sc = n - (n >>> 2);                 }             } finally {                 sizeCtl = sc;             }             break;         }     }     return tab; }

     sizeCtl默认为0,如果ConcurrentHashMap实例化时有传参数,sizeCtl会是一个2的幂次方的值。所以执行第一次put操作的线程会执行Unsafe.compareAndSwapInt方法修改sizeCtl为-1,有且只有一个线程能够修改成功,其它线程通过Thread.yield()让出CPU时间片等待table初始化完成。

    put操作

    假设table已经初始化完成,put操作采用CAS+synchronized实现并发插入或更新操作,具体实现如下。

    /** Implementation for put and putIfAbsent */ final V putVal(K key, V value, boolean onlyIfAbsent) {     if (key == null || value == null) throw new NullPointerException();     int hash = spread(key.hashCode());     int binCount = 0;     for (Node<K,V>[] tab = table;;) {         Node<K,V> f; int n, i, fh;         if (tab == null || (n = tab.length) == 0)             tab = initTable();         else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {             if (casTabAt(tab, i, null,                          new Node<K,V>(hash, key, value, null)))                 break;                   // no lock when adding to empty bin         }         else if ((fh = f.hash) == MOVED)             tab = helpTransfer(tab, f);         else {             V oldVal = null;             synchronized (f) {                 if (tabAt(tab, i) == f) {                     if (fh >= 0) {                         binCount = 1;                         for (Node<K,V> e = f;; ++binCount) {                             K ek;                             if (e.hash == hash &&                                 ((ek = e.key) == key ||                                  (ek != null && key.equals(ek)))) {                                 oldVal = e.val;                                 if (!onlyIfAbsent)                                     e.val = value;                                 break;                             }                             Node<K,V> pred = e;                             if ((e = e.next) == null) {                                 pred.next = new Node<K,V>(hash, key,                                                           value, null);                                 break;                             }                         }                     }                     else if (f instanceof TreeBin) {                         Node<K,V> p;                         binCount = 2;                         if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,                                                        value)) != null) {                             oldVal = p.val;                             if (!onlyIfAbsent)                                 p.val = value;                         }                     }                 }             }             if (binCount != 0) {                 if (binCount >= TREEIFY_THRESHOLD)                     treeifyBin(tab, i);                 if (oldVal != null)                     return oldVal;                 break;             }         }     }     addCount(1L, binCount);     return null; } hash算法 /**  * Spreads (XORs) higher bits of hash to lower and also forces top  * bit to 0. Because the table uses power-of-two masking, sets of  * hashes that vary only in bits above the current mask will  * always collide. (Among known examples are sets of Float keys  * holding consecutive whole numbers in small tables.)  So we  * apply a transform that spreads the impact of higher bits  * downward. There is a tradeoff between speed, utility, and  * quality of bit-spreading. Because many common sets of hashes  * are already reasonably distributed (so don't benefit from  * spreading), and because we use trees to handle large sets of  * collisions in bins, we just XOR some shifted bits in the  * cheapest possible way to reduce systematic lossage, as well as  * to incorporate impact of the highest bits that would otherwise  * never be used in index calculations because of table bounds.  */ static final int spread(int h) {     return (h ^ (h >>> 16)) & HASH_BITS; } table中定位索引位置,n是table的大小

        int index = (n - 1) & hash

    获取table中对应索引的元素f。 Doug Lea采用Unsafe.getObjectVolatile来获取,也许有人质疑,直接table[index]不可以么,为什么要这么复杂? 在java内存模型中,我们已经知道每个线程都有一个工作内存,里面存储着table的副本,虽然table是volatile修饰的,但不能保证线程每次都拿到table中的最新元素,Unsafe.getObjectVolatile可以直接获取指定内存的数据,保证了每次拿到数据都是最新的。如果f为null,说明table中这个位置第一次插入元素,利用Unsafe.compareAndSwapObject方法插入Node节点。

    如果CAS成功,说明Node节点已经插入,随后addCount(1L, binCount)方法会检查当前容量是否需要进行扩容。

    如果CAS失败,说明有其它线程提前插入了节点,自旋重新尝试在这个位置插入节点。

    如果f的hash值为-1,说明当前f是ForwardingNode节点,意味有其它线程正在扩容,则一起进行扩容操作。其余情况把新的Node节点按链表或红黑树的方式插入到合适的位置,这个过程采用同步内置锁实现并发,代码见上问:

    synchronized (f) {………}

    在节点f上进行同步,节点插入之前,再次利用tabAt(tab, i) == f判断,防止被其它线程修改。

    如果f.hash >= 0,说明f是链表结构的头结点,遍历链表,如果找到对应的node节点,则修改value,否则在链表尾部加入节点。如果f是TreeBin类型节点,说明f是红黑树根节点,则在树结构上遍历元素,更新或增加节点。如果链表中节点数binCount >= TREEIFY_THRESHOLD(默认是8),则把链表转化为红黑树结构。

    table扩容

    table容量不足的时候,即table的元素数量达到容量阈值sizeCtl,需要对table进行扩容。整个扩容分为两部分:

    构建一个nextTable,大小为table的两倍。把table的数据复制到nextTable中。

    这两个过程在单线程下实现很简单,但是ConcurrentHashMap是支持并发插入的,扩容操作自然也会有并发的出现,这种情况下,第二步可以支持节点的并发复制,这样性能自然提升不少,但实现的复杂度也上升了一个台阶。

    先看第一步,构建nextTable,毫无疑问,这个过程只能只有单个线程进行nextTable的初始化,具体实现如下:

    /**  * Adds to count, and if table is too small and not already  * resizing, initiates transfer. If already resizing, helps  * perform transfer if work is available.  Rechecks occupancy  * after a transfer to see if another resize is already needed  * because resizings are lagging additions.  *  * @param x the count to add  * @param check if <0, don't check resize, if <= 1 only check if uncontended  */ private final void addCount(long x, int check) {     CounterCell[] as; long b, s;     if ((as = counterCells) != null ||         !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {         CounterCell a; long v; int m;         boolean uncontended = true;         if (as == null || (m = as.length - 1) < 0 ||             (a = as[ThreadLocalRandom.getProbe() & m]) == null ||             !(uncontended =               U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {             fullAddCount(x, uncontended);             return;         }         if (check <= 1)             return;         s = sumCount();     }     if (check >= 0) {         Node<K,V>[] tab, nt; int n, sc;         while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&                (n = tab.length) < MAXIMUM_CAPACITY) {             int rs = resizeStamp(n);             if (sc < 0) {                 if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||                     sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||                     transferIndex <= 0)                     break;                 if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))                     transfer(tab, nt);             }             else if (U.compareAndSwapInt(this, SIZECTL, sc,                                          (rs << RESIZE_STAMP_SHIFT) + 2))                 transfer(tab, null);             s = sumCount();         }     } }

    通过Unsafe.compareAndSwapInt修改sizeCtl值,保证只有一个线程能够初始化nextTable,扩容后的数组长度为原来的两倍,但是容量是原来的1.5

    节点从table移动到nextTable,大体思想是遍历、复制的过程。

    首先根据运算得到需要遍历的次数i,然后利用tabAt方法获得i位置的元素f,初始化一个forwardNode实例fwd。如果f == null,则在table中的i位置放入fwd,这个过程是采用Unsafe.compareAndSwapObjectf方法实现的,很巧妙的实现了节点的并发移动。如果f是链表的头节点,就构造一个反序链表,把他们分别放在nextTable的i和i+n的位置上,移动完成,采用Unsafe.putObjectVolatile方法给table原位置赋值fwd。如果f是TreeBin节点,也做一个反序处理,并判断是否需要untreeify,把处理的结果分别放在nextTable的i和i+n的位置上,移动完成,同样采用Unsafe.putObjectVolatile方法给table原位置赋值fwd。

    遍历过所有的节点以后就完成了复制工作,把table指向nextTable,并更新sizeCtl为新数组大小的0.75 ,扩容完成。

    红黑树构造

    注意:如果链表结构中元素超TREEIFY_THRESHOLD值,默认为8个,则把链表转化为红黑树,提高遍历查询效率。

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

     

    if (binCount != 0) {     if (binCount >= TREEIFY_THRESHOLD)         treeifyBin(tab, i);     if (oldVal != null)         return oldVal;     break; }

    接下来我们看看如何构造树结构,代码如下:

    /* ---------------- Conversion from/to TreeBins -------------- */ /**  * Replaces all linked nodes in bin at given index unless table is  * too small, in which case resizes instead.  */ private final void treeifyBin(Node<K,V>[] tab, int index) {     Node<K,V> b; int n, sc;     if (tab != null) {         if ((n = tab.length) < MIN_TREEIFY_CAPACITY)             tryPresize(n << 1);         else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {             synchronized (b) {                 if (tabAt(tab, index) == b) {                     TreeNode<K,V> hd = null, tl = null;                     for (Node<K,V> e = b; e != null; e = e.next) {                         TreeNode<K,V> p =                             new TreeNode<K,V>(e.hash, e.key, e.val,                                               null, null);                         if ((p.prev = tl) == null)                             hd = p;                         else                             tl.next = p;                         tl = p;                     }                     setTabAt(tab, index, new TreeBin<K,V>(hd));                 }             }         }     } } /**  * Returns a list on non-TreeNodes replacing those in given list.  */ static <K,V> Node<K,V> untreeify(Node<K,V> b) {     Node<K,V> hd = null, tl = null;     for (Node<K,V> q = b; q != null; q = q.next) {         Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);         if (tl == null)             hd = p;         else             tl.next = p;         tl = p;     }     return hd; }

    可以看出,生成树节点的代码块是同步的,进入同步代码块之后,再次验证tableindex位置元素是否被修改过。1、根据tableindex位置Node链表,重新生成一个hd为头结点的TreeNode链表。2、根据hd头结点,生成TreeBin树结构,并把树结构的root节点写到tableindex位置的内存中,具体实现如下:

    /**  * Creates bin with initial set of nodes headed by b.  */ TreeBin(TreeNode<K,V> b) {     super(TREEBIN, null, null, null);     this.first = b;     TreeNode<K,V> r = null;     for (TreeNode<K,V> x = b, next; x != null; x = next) {         next = (TreeNode<K,V>)x.next;         x.left = x.right = null;         if (r == null) {             x.parent = null;             x.red = false;             r = x;         }         else {             K k = x.key;             int h = x.hash;             Class<?> kc = null;             for (TreeNode<K,V> p = r;;) {                 int dir, ph;                 K pk = p.key;                 if ((ph = p.hash) > h)                     dir = -1;                 else if (ph < h)                     dir = 1;                 else if ((kc == null &&                           (kc = comparableClassFor(k)) == null) ||                          (dir = compareComparables(kc, k, pk)) == 0)                     dir = tieBreakOrder(k, pk);                     TreeNode<K,V> xp = p;                 if ((p = (dir <= 0) ? p.left : p.right) == null) {                     x.parent = xp;                     if (dir <= 0)                         xp.left = x;                     else                         xp.right = x;                     r = balanceInsertion(r, x);                     break;                 }             }         }     }     this.root = r;     assert checkInvariants(root); }

    主要根据Node节点的hash值大小构建二叉树。这个红黑树的构造过程实在有点复杂,感兴趣的同学可以看看源码。

    get操作

    /**  * Returns the value to which the specified key is mapped,  * or {@code null} if this map contains no mapping for the key.  *  * <p>More formally, if this map contains a mapping from a key  * {@code k} to a value {@code v} such that {@code key.equals(k)},  * then this method returns {@code v}; otherwise it returns  * {@code null}.  (There can be at most one such mapping.)  *  * @throws NullPointerException if the specified key is null  */

    public V get(Object key) {     Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;     int h = spread(key.hashCode());     if ((tab = table) != null && (n = tab.length) > 0 &&         (e = tabAt(tab, (n - 1) & h)) != null) {         if ((eh = e.hash) == h) {             if ((ek = e.key) == key || (ek != null && key.equals(ek)))                 return e.val;         }         else if (eh < 0)             return (p = e.find(h, key)) != null ? p.val : null;         while ((e = e.next) != null) {             if (e.hash == h &&                 ((ek = e.key) == key || (ek != null && key.equals(ek))))                 return e.val;         }     }     return null;}

    get操作和put操作相比,显得简单了许多。

     

    判断table是否空,如果空,直接返回null计算keyhash值,并获取指定table中指定位置的Node节点,通过遍历链表或则树结构找到对应的节点,返回value

    总结

    ConcurrentHashMap 是一个并发散列映射表的实现,它允许完全并发的读取,并且支持给定数量的并发更新。相比于 HashTable 和同步包装器包装的 HashMap,使用一个全局的锁来同步不同线程间的并发访问,同一时间点,只能有一个线程持有锁,也就是说在同一时间点,只能有一个线程能访问容器,这虽然保证多线程间的安全并发访问,但同时也导致对容器的访问变成串行化的了。

    get() 方法弱一致性

    ConcurrentHashMap的get方法是弱一致的,是什么含义?可能你期望往ConcurrentHashMap底层数据结构中加入一个元素后,立马能对get可见,但ConcurrentHashMap并不能如你所愿。换句话说,put操作将一个元素加入到底层数据结构后,get可能在某段时间内还看不到这个元素,若不考虑内存模型,单从代码逻辑上来看,却是应该可以看得到的。

    最新回复(0)