美文网首页
ConcurrentHashMap源码分析

ConcurrentHashMap源码分析

作者: 一路花开_8fab | 来源:发表于2018-09-15 18:23 被阅读0次

1. 为什么需要ConcurrentHashMap

  • HashMap不是线程安全的,多线程环境下使用会导致CPU占用100%等问题
  • Hashtable 本身比较低效,因为它的实现基本就是将 put、get、size 等各种方法加上“synchronized”
  • SynchronizedMap中所有操作虽然不再声明成synchronized方法,但是还是利用了“this”作为互斥mutex,没有真正意义上的改进。
  public V put(K key, V value) {
      synchronized (mutex) {return m.put(key, value);}
  }

2. 早期的HashMap

其核心是利用分段设计,在进行并发操作的时候,只需要锁定相应段,这样就有效避免了类似HashTable整体同步的问题,大大提高了性能。

image.png

对于put操作,首先通过二次哈希避免哈希冲突,然后以Unsafe调用方式,直接获取相应的Segment,核心的逻辑在put操作中:

image.png

ConcurentHashMap会获取再入锁,然后进入线程安全的put操作。

image.png

3. java8和之后版本的ConcurrentHashMap

java 8之后,ConcurrentHashMap发生的主要变化有以下几点:

  • 不再使用 Segment,内部存储和HashMap结构非常相似
  • 大量使用CAS操作,在特定场景进行无锁并发操作

3.1 数据存储

 static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        volatile V val;
        volatile Node<K,V> next;

        ......
}

val和next都是用volatile修饰,保证多线程环境下的可见性。

3.2 初始化

因为不再使用 Segment,初始化操作大大简化,修改为 lazy-load 形式,这样可以有效避免初始开销。如果多个线程同时对数组进行初始化,如何保证只有一个线程能够初始化成功呢?
这是一个典型的CAS使用场景,利用 volatile 的 sizeCtl 作为互斥手段,来看下官方对sizeCtl 变量的解释,sizeCtl 变量有以下几种取值:

  1. 负数
    • -1代表数组正在初始化
    • -(1+扩容线程数量)代表数组正在扩容
  2. 0或正数
    • 数组初始化前,值为0,或通过构造器传入的初始值
    • 数组初始化后,值为下一次发生扩容的阈值,也即0.75*数组长度
  /**
     * Table initialization and resizing control.  When negative, the
     * table is being initialized or resized: -1 for initialization,
     * else -(1 + the number of active resizing threads).  Otherwise,
     * when table is null, holds the initial table size to use upon
     * creation, or 0 for default. After initialization, holds the
     * next element count value upon which to resize the table.
     */
    private transient volatile int sizeCtl;

查看initTable的源码可以看出,多个线程同时进行数组初始化时,若某个线程通过CAS操作成功将sizeCtl的值修改为-1,则由该线程负责具体的初始化过程,而其它线程由于CAS操作失败,什么都不做,就spin在那里,等待条件恢复。

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

3.3 put操作

  • 若索引位置没有元素,则进行CAS无锁线程安全的插入操作
  • 若索引位置已经有元素,则使用synchronized保证插入的线程安全
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;
    }

相关文章

网友评论

      本文标题:ConcurrentHashMap源码分析

      本文链接:https://www.haomeiwen.com/subject/bkltnftx.html