Java集合源码分析(六)——ConcurrentHashMap

简介

ConcurrentHashMap 是一个线程安全的散列表,存储的内容是键值对映射。
ConcurrentHashMap 继承于AbstractMap,实现了ConcurrentMap、Serializable接口。
ConcurrentHashMap 存储的键值对是无序的。

源码分析

父类

  • AbstractMap

接口

  • ConcurrentMap
  • Serializable

字段

	// 数组最大容量
    private static final int MAXIMUM_CAPACITY = 1 << 30;
	// 数组初始默认容量
    private static final int DEFAULT_CAPACITY = 16;
	// 将HashMap转化为数组输出的最大容量
    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
	// 默认并发级别
    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
	// 默认加载因子
    private static final float LOAD_FACTOR = 0.75f;
    // 树化阈值
    static final int TREEIFY_THRESHOLD = 8;
	// 树退化阈值
    static final int UNTREEIFY_THRESHOLD = 6;
	// 最小数化的数组大小
    static final int MIN_TREEIFY_CAPACITY = 64;
	// 扩容线程每次最少要迁移16个hash桶
    private static final int MIN_TRANSFER_STRIDE = 16;
	// 
    private static int RESIZE_STAMP_BITS = 16;
    // 
    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
	// 
    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;

    static final int MOVED     = -1; // 表示正在转移
    static final int TREEBIN   = -2; // 表示已经转移为树了
    static final int RESERVED  = -3; // 保留
    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash

    // CPU的数量
    static final int NCPU = Runtime.getRuntime().availableProcessors();
    // 保存节点的数组
    transient volatile Node<K,V>[] table;
	// 转移的时候用来保存数据的数组
    private transient volatile Node<K,V>[] nextTable;
    // 用于计算元素数量
	transient volatile long baseCount;
	// 用来控制表的初始化和扩容,当在初始化的时候指定了大小,这会将这个大小保存在sizeCtl中,
	// 大小为数组的0.75,
	// 当为负的时候,说明表正在初始化或扩张,
	// -1表示初始化,-(1+n) n:表示活动的扩张线程
    private transient volatile int sizeCtl;
	// 转移数组时的索引
    private transient volatile int transferIndex;

	// 区间忙位标志,标识当前cell数组是否在初始化或扩容中的CAS标志位
    private transient volatile int cellsBusy;
	// 用于计数,初始容量为2,采用区间计数法,一个槽位表示map数组一个区间的增量
    private transient volatile CounterCell[] counterCells;

    // 用于返回集合
    private transient KeySetView<K,V> keySet;
    private transient ValuesView<K,V> values;
    private transient EntrySetView<K,V> entrySet;

内部类

1.链表节点结构

 static class Node<K,V> implements Map.Entry<K,V> {
 		// Key的Hash值
        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;
        }

        public final K getKey()       { return key; }
        public final V getValue()     { return val; }
        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
        public final String toString(){ return key + "=" + val; }
        public final V setValue(V value) {
            throw new UnsupportedOperationException();
        }

        public final boolean equals(Object o) {
            Object k, v, u; Map.Entry<?,?> e;
            return ((o instanceof Map.Entry) &&
                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
                    (v = e.getValue()) != null &&
                    (k == key || k.equals(key)) &&
                    (v == (u = val) || v.equals(u)));
        }

        /**
         * Virtualized support for map.get(); overridden in subclasses.
         */
        Node<K,V> find(int h, Object k) {
            Node<K,V> e = this;
            if (k != null) {
                do {
                    K ek;
                    if (e.hash == h &&
                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
                        return e;
                } while ((e = e.next) != null);
            }
            return null;
        }
    }

2.树根结构

树根不会用来存储数据。

    static final class TreeBin<K,V> extends Node<K,V> {
        TreeNode<K,V> root;
        volatile TreeNode<K,V> first;
        volatile Thread waiter;
        volatile int lockState;
        // values for lockState
        static final int WRITER = 1; // set while holding write lock
        static final int WAITER = 2; // set when waiting for write lock
        static final int READER = 4; // increment value for setting read lock

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

		// 省略内部方法
    }

3.树节点结构

树节点用来存储数据,继承了Node数据提交给了父节点。

    static final class TreeNode<K,V> extends Node<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;

        TreeNode(int hash, K key, V val, Node<K,V> next,
                 TreeNode<K,V> parent) {
            // 数据给了父节点中的字段
            super(hash, key, val, next);
            this.parent = parent;
        }

        Node<K,V> find(int h, Object k) {
            return findTreeNode(h, k, null);
        }

        // 遍历树
        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
            if (k != null) {
                TreeNode<K,V> p = this;
                do  {
                    int ph, dir; K pk; TreeNode<K,V> q;
                    TreeNode<K,V> pl = p.left, pr = p.right;
                    if ((ph = p.hash) > h)
                        p = pl;
                    else if (ph < h)
                        p = pr;
                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
                        return p;
                    else if (pl == null)
                        p = pr;
                    else if (pr == null)
                        p = pl;
                    else if ((kc != null ||
                              (kc = comparableClassFor(k)) != null) &&
                             (dir = compareComparables(kc, k, pk)) != 0)
                        p = (dir < 0) ? pl : pr;
                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
                        return q;
                    else
                        p = pl;
                } while (p != null);
            }
            return null;
        }
    }

方法

1.构造方法

	// 无参数
    public ConcurrentHashMap() {
    }
	// 初始化容量
    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;
    }
	// 初始化填入原有map
    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        this.sizeCtl = DEFAULT_CAPACITY;
        putAll(m);
    }
	// 初始化让容量和加载因子
    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
        this(initialCapacity, loadFactor, 1);
    }
	// 初始化容量、加载因子和并发级别
    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        // 边界判断
        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
            throw new IllegalArgumentException();
        // 如果初始容量小于并发级别,就会将初始容量设置为并发级别大小
        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
        // 进行扩容
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        this.sizeCtl = cap;
    }

2.基本并发方法

	// 用来返回数据指定位置的节点的原子操作
    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
    }
	// 利用CAS方法,在数组指定位置设置值
    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                        Node<K,V> c, Node<K,V> v) {
        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
    }
	// 在数组指定位置设置值的原子操作
    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
    }

ConcurrentHashMap对数组的基本操作都是基于这几个方法的,通过直接操作内存的方法来保证并发处理的安全性,是基于硬件的安全机制。

3.初始化表数组的操作

private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        // 自旋操作,进行初始化
        while ((tab = table) == null || tab.length == 0) {
            if ((sc = sizeCtl) < 0)
            	// 如果发现sizeCtl小于0,说明有别的线程正在初始化或者扩容表
            	// 那就让当前线程退出运行态,变成就绪态
                Thread.yield(); // lost initialization race; just spin
            // 通过CAS的操作将SIZECTL替换为-1,sc是原来读取的值
            // 会不断循环进行操作
            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;
                        // sizeCtl长度为数组长度的0.75
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

在第一次的修改操作中,发现数据表没有被初始化的时候,就会调用这个方法进行初始化。

4.修改添加元素

	// 设置指定键的值
    public V put(K key, V value) {
        return putVal(key, value, false);
    }

    // onlyIfAbsent 如果为true,那就只会在key为空的时候添加值
    final V putVal(K key, V value, boolean onlyIfAbsent) {
    	// 键值都不能为空
        if (key == null || value == null) throw new NullPointerException();
        // 计算key的哈希值
        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();
            // 通过key的哈希值计算对应的槽位,(n - 1) & hash)和之前的HashMap一样,取余
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            	// 如果对应槽位是空的,那么就通过CAS添加节点
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            // 如果检测到当前节点hash是MOVED,说明数组正在扩容或者转移,当前线程就去帮帮
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
            	// 现在什么事情都没有,可以安心查找链表或者树种的节点了
                V oldVal = null;
                // 通过同步阻塞的方式,给头节点加锁,这样其他线程就不能来操作这个槽位了
                // 同时也不会影响其他线程操作其他槽位然后再进行查询
                synchronized (f) {
                	// 再次比较当前头是不是原来的那个头,因为可能中途又被修改了
                    if (tabAt(tab, i) == f) {
                    	// 取出来的元素的hash值大于0,说明是链表,当转换为树之后,hash值为-2
                        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;
                                    //当使用putIfAbsent的时候,只有在这个key没有设置值得时候才设置
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                // 节点种没有对应的key,那就在最后新建一个节点存下来
                                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;
                }
            }
        }
        // 用来给整个MAP计数,可能会触发扩容
        addCount(1L, binCount);
        return null;
    }

5.统计元素数量

这个方法是用于在多线程下安全统计使用的。

	// 在每次对表可能会产生修改的地方调用,对表的容量进行计数,然后再判断是否需要扩容
	// 如果不为空,且CAS竞争失败,说明存在竞争,就不用使用baseCount来累加计数,需要通过counterCells
    private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        // 如果counterCells为空,就采用CAS修改baseCount变量
        if ((as = counterCells) != null ||
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
            CounterCell a; long v; int m;
            // 设置冲突标志
            boolean uncontended = true;
            // 如果counterCell为空, 或随机获取一个数组的位置为空,或用CAS随机修改一个位置的值失败
            // 那就调用fullAddCount方法
            if (as == null || (m = as.length - 1) < 0 ||
                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
                !(uncontended =
                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
                // 用于初始化counterCell,记录元素个数,里面也包括扩容
                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;
                    // CAS的方法进行尝试扩容
                    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();
            }
        }
    }
	
	// 进行计数
    final long sumCount() {
        CounterCell[] as = counterCells; CounterCell a;
        long sum = baseCount;
        if (as != null) {
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null)
                	// 将counterCells中的变化量累加到baseCount
                    sum += a.value;
            }
        }
        return sum;
    }
 
 // 对CounterCell 进行初始化,或出现竞争情况下进行插入
 private final void fullAddCount(long x, boolean wasUncontended) {
        int h;
        // 用于产生随机数
        if ((h = ThreadLocalRandom.getProbe()) == 0) {
            ThreadLocalRandom.localInit();      // force initialization
            h = ThreadLocalRandom.getProbe();
            wasUncontended = true;
        }
        boolean collide = false;                // True if last slot nonempty
        for (;;) {
            CounterCell[] as; CounterCell a; int n; long v;
            // 计数数组已经初始化
            if ((as = counterCells) != null && (n = as.length) > 0) {
            	// 数组中对应区间槽位没有元素
                if ((a = as[(n - 1) & h]) == null) {
                	// 数组非忙,说明没有其他线程在修改
                    if (cellsBusy == 0) {            // Try to attach new Cell
                    	// 实例化一个计数元素对象,放入计数值
                        CounterCell r = new CounterCell(x); // Optimistic create
                        // 通过CAS方法获取数组的修改权
                        if (cellsBusy == 0 &&
                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                            boolean created = false;
                            try {               // Recheck under lock
                                CounterCell[] rs; int m, j;
                                // 再次校验
                                if ((rs = counterCells) != null &&
                                    (m = rs.length) > 0 &&
                                    rs[j = (m - 1) & h] == null) {
                                    // 把对象插入数组
                                    rs[j] = r;
                                    created = true;
                                }
                            } finally {
                                cellsBusy = 0;
                            }
                            if (created)
                                break;
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
                    break;
                // 放置数组一致扩容,最大的容量就是CPU的核心数
                else if (counterCells != as || n >= NCPU)
                    collide = false;            // At max size or stale
                else if (!collide)
                    collide = true;
                // CAS竞争数组修改权
                else if (cellsBusy == 0 &&
                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                    try {
                        if (counterCells == as) {// Expand table unless stale
                        	// 进行扩容
                            CounterCell[] rs = new CounterCell[n << 1];
                            for (int i = 0; i < n; ++i)
                                rs[i] = as[i];
                            counterCells = rs;
                        }
                    } finally {
                        cellsBusy = 0;
                    }
                    collide = false;
                    continue;                   // Retry with expanded table
                }
                // 原来的位置存在数组,那就重新获取随机值,直到成功插入空位
                h = ThreadLocalRandom.advanceProbe(h);
            }
            else if (cellsBusy == 0 && counterCells == as &&
                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                boolean init = false;
                try {                           // Initialize table
                    if (counterCells == as) {
                    	// 计数数组的初始化,默认容量是2
                        CounterCell[] rs = new CounterCell[2];
                        rs[h & 1] = new CounterCell(x);
                        counterCells = rs;
                        init = true;
                    }
                } finally {
                    cellsBusy = 0;
                }
                if (init)
                    break;
            }
            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
                break;                          // Fall back on using base
        }
    }

6.扩容

 // 扩容的大小的默认值,因为每次需要扩2的幂次,所以通过这个操作,可以得到大于期望容量的最小值
 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;
 }
 // 尝试扩容
 private final void tryPresize(int size) {
 		// 最大容量判断,否则使用tableSizeFor算出来的扩容大小
        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
            tableSizeFor(size + (size >>> 1) + 1);
        int sc;
        while ((sc = sizeCtl) >= 0) {
            Node<K,V>[] tab = table; int n;
            // 如果还没有被初始化,那就初始化一个刚才算出来大小的数组
            if (tab == null || (n = tab.length) == 0) {
                n = (sc > c) ? sc : c;
                // 和上面初始化操作一样,采用CAS,保证再初始化的时候,只有当前线程在操作
                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                    try {
                        if (table == tab) {
                            @SuppressWarnings("unchecked")
                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                            table = nt;
                            // sc为容量的0.75
                            sc = n - (n >>> 2);
                        }
                    } finally {
                        sizeCtl = sc;
                    }
                }
            }
            // 计算出来的容量小于扩容阈值或者大于上限,就退出扩容
            else if (c <= sc || n >= MAXIMUM_CAPACITY)
                break;
            else if (tab == table) {
                int rs = resizeStamp(n);
                if (sc < 0) {
                    Node<K,V>[] nt;
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                    // transfer的线程数加一,该线程将进行transfer的帮忙
                    // 在transfer的时候,sc表示在transfer工作的线程数
                    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);
            }
        }
    }

// 扩容的具体方法
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        // MIN_TRANSFER_STRIDE用来必变占用太多CPU线程
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
		// 如果目标的表位空的时候,说明该线程是本次扩容第一个进来的线程
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                // 初始化一个两倍于原表的新表
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                nextTab = nt;
            } catch (Throwable ex) {      // try to cope with OOME
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            // 更新成员变量
            nextTable = nextTab;
            transferIndex = n;
        }
        int nextn = nextTab.length;
        // 创建一个fwd节点,用来控制并发,当一个节点为空或已经被转移之后,就设置它为fwd节点,所以这是一个空的标志
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        // 是否继续向前查找的标志
        boolean advance = true;
        // 在完成之前重写扫描一遍数组,看看有没有完成
        boolean finishing = false; // to ensure sweep before committing nextTab
        // 开始遍历
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            while (advance) {
                int nextIndex, nextBound;
                if (--i >= bound || finishing)
                    advance = false;
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                // 已经完成扩容转移
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    finishing = advance = true;
                    i = n; // recheck before commit
                }
            }
            else if ((f = tabAt(tab, i)) == null)
            	// 把数组中null元素设置为fwd节点
                advance = casTabAt(tab, i, null, fwd);
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
            	// 加锁
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        // 当前节点是链表
                        if (fh >= 0) {
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            // 将原来的节点放到新的位置上去
                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
                                int ph = p.hash; K pk = p.key; V pv = p.val;
                                if ((ph & n) == 0)
                                    ln = new Node<K,V>(ph, pk, pv, ln);
                                else
                                    hn = new Node<K,V>(ph, pk, pv, hn);
                            }
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                        // 复制树
                        else if (f instanceof TreeBin) {
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            // 构造一个双向链表,把数据放到双向链表中
                            TreeNode<K,V> lo = null, loTail = null;
                            TreeNode<K,V> hi = null, hiTail = null;
                            int lc = 0, hc = 0;
                            for (Node<K,V> e = t.first; e != null; e = e.next) {
                                int h = e.hash;
                                TreeNode<K,V> p = new TreeNode<K,V>
                                    (h, e.key, e.val, null, null);
                                if ((h & n) == 0) {
                                    if ((p.prev = loTail) == null)
                                        lo = p;
                                    else
                                        loTail.next = p;
                                    loTail = p;
                                    ++lc;
                                }
                                else {
                                    if ((p.prev = hiTail) == null)
                                        hi = p;
                                    else
                                        hiTail.next = p;
                                    hiTail = p;
                                    ++hc;
                                }
                            }
                            // 复制完树之后,判断树是不是需要退化
                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                    }
                }
            }
        }
    }

几个要点:

  • 复制之后新的链表不是旧链表的绝对倒序;
  • 库容的时候每个线程都有处理的步长,最少为16,这个步长范围内的节点只有一个线程来出来。
  • 扩容的触发、扩多少和HashMap保持一致。

7.获取元素

	// 通过键获取对应的值
    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;
    }

从这里可以看出,ConcurrentHashMap对读操作不加锁。

总结

源码总结

1.扩容

扩容的触发和扩容的大小基本和HashMap保持一致。

扩容触发条件:

  • 容量为0的时候插入元素,触发的初始化扩容;
  • 现有键值对数量大小是否大于扩容阈值,所谓扩容阈值,就是容量与加载因子的积,默认是0.75;
  • 如果在数组容量小于默认最小树化阈值64的时候触发了树化,那么就会进行一次扩容;
  • 对于put操作,扩容是发生在元素添加之后,这与List不同。

扩容的大小:

  • 初始默认容量是16。
  • 每次扩容的大小是2的幂次。

2.树化

树化的条件:

  • 当一个槽里的链表节点数大于等于树化阈值8,就可能会将链表生成红黑树。
  • 树化的还有一个条件是 键值对的容量必须大于64,这样可以避免一开始的时候数组比较小,大量的节点刚好被放到一个槽中,导致不必要的转化。

树退化的条件:

  • 如果树的节点数小于退化树阈值,就会将红黑树退化为链表。
  • 退化树阈值默认为6。

3.计数

在高并发环境下,对map的节点数进行计数就需要保证计数值的安全。

计数原理:
首先依赖两个成员变量:

  • baseCount:基准量,也就是不存在竞争的时候,直接操作这个值可以了。
  • counterCells:是一个数组,初始化的大小为2 ,每次扩容也是两倍,但是不会超过CPU的核数。高并发环境下使用,每个线程都有一个探针HASH值,通过这个哈希值定位到数组对应槽的位置,然后通过CAS的方法将当前线程的增量写到线程对应的槽里。最后需要统计数量的时候,将所有槽内的数据和基准值加在一起就好了。

计数过程:

  1. 每当map被修改了之后,都会进行一次计数操作,以判断是否需要扩容什么的;
  2. 计数的时候首先判断是存在并发竞争,如果不存在,就直接将当前的操作增量加到基准值中去;如果存在竞争,就利用counterCells,将当前线程的增量写到自己对应的槽位中去;
  3. 最后将所有槽位的增量累加到基准值,就是最后的统计结果了。
posted @ 2020-12-03 11:36  lippon  阅读(128)  评论(0编辑  收藏  举报