ConcurrentHashMap源码分析

本文详细分析了Java 8中ConcurrentHashMap的源码,包括其容量控制、构造方法、put操作以及并发控制策略。在put过程中,ConcurrentHashMap采用了分段锁和CAS操作来保证线程安全,当链表长度达到一定阈值时,会转换为红黑树以提高查找效率。此外,文章还介绍了在扩容时如何进行线程协作,确保并发扩容的正确性和高效性。
摘要由CSDN通过智能技术生成

ConcurrentHashMap源码分析,基于jdk8,

1、一些属性值

//最大容量
private static final int MAXIMUM_CAPACITY = 1 << 30;
//默认容量
private static final int DEFAULT_CAPACITY = 16;
//最大数组长度
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//负载因子
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;
//扩容时每个cpu处理最小的桶的个数,因为会出现多个线程共同扩容
private static final int MIN_TRANSFER_STRIDE = 16;
//扩容戳位数
private static int RESIZE_STAMP_BITS = 16;
//最大扩容线程数 65535
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
//16 扩容戳移动位数
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
//cpu核心数
static final int NCPU = Runtime.getRuntime().availableProcessors();
//数组
transient volatile Node<K,V>[] table;
//扩容时使用的数组
private transient volatile Node<K,V>[] nextTable;
//和counterCells共同记录map元素个数
private transient volatile long baseCount;
//扩容阈值   非扩容时是扩容阈值,扩容时是负数,表示在扩容,高16位是扩容标记,低16位是扩容线程数+1
private transient volatile int sizeCtl;
//扩容下标
private transient volatile int transferIndex;
//
private transient volatile int cellsBusy;
//记录元素个数的数组 初始化时容量是2,分片思想,增加写map个数的并发
private transient volatile CounterCell[] counterCells;
//该桶正在扩容
static final int MOVED     = -1; // hash for forwarding nodes
static final int TREEBIN   = -2; // hash for roots of trees
static final int RESERVED  = -3; // hash for transient reservations
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash

2、构造方法

//无参构造方法,初始化方法在put方法里面
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;
    }
	//带初始容量和负载因子的构造方法
	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;
    }

3、容量控制方法

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

4、put分析

public V put(K key, V value) {
        return putVal(key, value, false);
    }
	final V putVal(K key, V value, boolean onlyIfAbsent) {
		//concurrentHashMap的key和value都不允许为空,这和hashmap有区别
        if (key == null || value == null) throw new NullPointerException();
		//计算hash
        int hash = spread(key.hashCode());
		//是否需要树化的变量
        int binCount = 0;
		//for循环,因为是线程安全的,多线程操作的时候用的,和hashmap有区别
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
			//初始化concurrenthashmap,初始化完成后并未跳出循环,下次循环会设值
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //如果对应下标不存在元素,则用cas将元素放入数组,因为可能同时多个Node放入相同位置,所以使用cas,放入成功则跳出循环
			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
            }
			//如果当前的hash桶在扩容转移,则协助扩容
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
			//没有在扩容,hash桶中已经存在元素,设值
            else {
				//先看这段,这段才扩容,之后才会有上面的协助扩容
				//保存旧的值,因为可能是覆盖元素值
                V oldVal = null;
				//加锁,锁住的是数组的元素,也就是链表的头节点或者红黑树的根节点,单个的hash桶
                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;
								//将Node挂在链表的末尾
                                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;
    }
//计算hesh的方法
	static final int spread(int h) {
        return (h ^ (h >>> 16)) & HASH_BITS;
    }
//初始化concurrenthashmap的方法
	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;
    }
//cas设置node
	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> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
    }
//链表转红黑树
	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));
                    }
                }
            }
        }
    }
//预扩容方法
	private final void tryPresize(int size) {
        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;
                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 = n - (n >>> 2);
                        }
                    } finally {
                        sizeCtl = sc;
                    }
                }
            }
			//不能再扩容了
            else if (c <= sc || n >= MAXIMUM_CAPACITY)
                break;
            else if (tab == table) {
				//生成扩容戳,高16位是扩容标记,低16位是扩容线程数,低16位最高位是1
				//由当前容量决定,不一样的值,代表不同的容量扩容,可作为扩容唯一标记
                int rs = resizeStamp(n);
				//然后在看这里,这里为协助扩容
				//正在扩容,sc的解释在下面
                if (sc < 0) {
                    Node<K,V>[] nt;
					//(sc >>> RESIZE_STAMP_SHIFT) != rs 比较扩容戳和sc右移16位后的值,sc右移16位后高16位全是0,如果相等,代表扩容结束
					//sc == rs + 1 扩容结束
					//sc == rs + MAX_RESIZERS 达到最大扩容线程数
					//transferIndex <= 0 所有的Node都分配了线程
					//(nt = nextTable) == null
                    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);
                }
				//扩容时先看这里,这里代表第一个线程在扩容
				//rs << RESIZE_STAMP_SHIFT 低16位移到高16位,为负数
				//当前没有在扩容,将sc设置为负数,+2为有一个线程在扩容
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
            }
        }
    }
//生成扩容戳的方法
static final int resizeStamp(int n) {
		//Integer.numberOfLeadingZeros(n) 统计最高位1前面的的0的数量
		//(1 << (RESIZE_STAMP_BITS - 1))  将1移到低16位的最高位
        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
    }
//扩容方法
	private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        //获取每个线程处理的桶数量  最小处理16个
		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;
		//标志正在转移的节点,hash为 MOVED -1
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        //标志向前移动,就是还需要扩容下一个桶
		boolean advance = true;
		//是否扩容完成
        boolean finishing = false; // to ensure sweep before committing nextTab
        //通过 for 自循环处理每个槽位中的链表元素,默认 advace 为真,
		//通过 CAS 设置transferIndex 属性值,并初始化 i 和 bound 值, 
		//i 指当前处理的槽位序号, bound 指需要处理的槽位边界,先处理槽位 15 的节点
		for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            while (advance) {
				//正在处理的下标
                int nextIndex, nextBound;
				//--i表示下一个待处理的桶,如果>=bound,表示当前线程已经分配过桶
                if (--i >= bound || finishing)
                    advance = false;
				//表示所有桶已经分配完毕   16
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
				//修改TRANSFERINDEX,为当前线程分配任务,处理节点区间(nextBound, nextIndex)
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
						 //16 > 16 ? 0 : 0
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;// 0
                    i = nextIndex - 1;// 15 下面会处理这个下标
                    advance = false;
                }
            }
			//已经遍历完旧数组,当前线程已经处理完所有负责的桶
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                if (finishing) {//完成了扩容,
                    nextTable = null;//将扩容使用的数组置空
                    table = nextTab;//将数组重新赋值
                    sizeCtl = (n << 1) - (n >>> 1);//更新扩容阈值
                    return;
                }
				//SIZECTL 原始扩容是 (rs << RESIZE_STAMP_SHIFT) + 2
				//每增加一个协助扩容线程就+1
				//协助扩容线程执行完成就-1
                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)
                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) {
							//区分低链高链,也就是在原数组下标还是新扩容的数组下标,为0,则在低链,不为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;
                            }
							//头插法,将链表节点拆分成两个链表,并将ln,hn指向两个链表的头节点
                            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;
                        }
                    }
                }
            }
        }
    }
//给下标设置值
	static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
    }
//协助扩容方法
	final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
        Node<K,V>[] nextTab; int sc;
		//判断是否正在扩容,如果正在扩容,则进入
        if (tab != null && (f instanceof ForwardingNode) &&
            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
            //生成扩容戳,高16位是扩容标记,低16位是扩容线程数
			int rs = resizeStamp(tab.length);
			//判断是否还在扩容,
            while (nextTab == nextTable && table == tab &&
                   (sc = sizeCtl) < 0) {//循环尝试将当前线程加入扩容线程中
				//(sc >>> RESIZE_STAMP_SHIFT) != rs 比较扩容戳和sc右移16位后的值,sc右移16位后高16位全是0,如果相等,代表扩容结束
				//sc == rs + 1 扩容结束
				//sc == rs + MAX_RESIZERS 达到最大扩容线程数
				//transferIndex <= 0 所有的Node都分配了线程
                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
                    break;
				//增加扩容线程数
                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                    //扩容
					transfer(tab, nextTab);
                    break;
                }
            }
            return nextTab;
        }
        return table;
    }

5、增加map元素个数方法

private final void addCount(long x, int check) {
        //map的元素个数放在数组里面,总数是各个元素相加,分片思想
		CounterCell[] as; long b, s;
		//counterCells 不为空 || 原子修改basecount失败(存在线程竞争)
        if ((as = counterCells) != null ||
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
            CounterCell a; long v; int m;
            boolean uncontended = true;
			//counterCells 为空
			//随机选择counterCells 下标为空
			//cas设置a的value失败
			//if条件里面就是随机选择counterCells的一个下标,然后增加其value的值,失败说明有线程竞争
            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)//链表长度小于等于1,不用扩容
                return;
            s = sumCount();//统计map元素个数
        }
		//链表长度>=0,检查是否需要扩容
        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;
					//扩容线程数+1,协助扩容
                    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();
            }
        }
    }
//初始化counterCells以及扩容方法
	private final void fullAddCount(long x, boolean wasUncontended) {
        int h;
		//初始化随机值
        if ((h = ThreadLocalRandom.getProbe()) == 0) {
            ThreadLocalRandom.localInit();      // force initialization
            h = ThreadLocalRandom.getProbe();
            wasUncontended = true;
        }
		//最后的数组元素非空时 为 true
        boolean collide = false;                // True if last slot nonempty
        for (;;) {
            CounterCell[] as; CounterCell a; int n; long v;
			//counterCells初始化过了
            if ((as = counterCells) != null && (n = as.length) > 0) {
                //随机选择的 counterCells 下标为空
				if ((a = as[(n - 1) & h]) == null) {
                    if (cellsBusy == 0) {            // 没有在初始化或扩容
                        CounterCell r = new CounterCell(x); // 封装一个 CounterCell
                        //获得操作权限,避免其他线程并发操作
						if (cellsBusy == 0 &&
                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                            boolean created = false;
                            try {               // 将刚封装的CounterCell设置给对应的 counterCells 的下标
                                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
                //如果cas直接操作下标元素数值增加成功
				else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
                    break;
				//如果创建了新的 counterCells (扩容了) 或者 counterCells 的容量大于cpu核心数(最多支持cpu核心数的线程并发)
                else if (counterCells != as || n >= NCPU)
                    collide = false;            // At max size or stale //当前线程循环失败,不进行操作
                else if (!collide)
                    collide = true; //恢复 collide 下次循环再判断是否需要操作
                //扩容 容量为原来的2倍
				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);
            }//没有初始化counterCells 开始初始化
            else if (cellsBusy == 0 && counterCells == as &&
                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                boolean init = false;
                try {                           // Initialize table
					//初始化counterCells并且随机选择一个下标将其值设置为要增加的元素个数的值
                    if (counterCells == as) {
                        CounterCell[] rs = new CounterCell[2];
                        rs[h & 1] = new CounterCell(x);
                        counterCells = rs;
                        init = true;
                    }
                } finally {
                    cellsBusy = 0;//表示未扩容,未在初始化
                }
                if (init)
                    break;
            }//直接cas修改basecount
            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
                break;                          // Fall back on using base
        }
    }
//统计map元素个数的方法
	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)
                    sum += a.value;
            }
        }
        return sum;
    }

6、静态内部类

节点
//普通节点
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;
        }

        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;
        }
    }
	
//正在转移的节点,hash为-1 MOVED
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;
        }

        Node<K,V> find(int h, Object k) {
            // loop to avoid arbitrarily deep recursion on forwarding nodes
            outer: for (Node<K,V>[] tab = nextTable;;) {
                Node<K,V> e; int n;
                if (k == null || tab == null || (n = tab.length) == 0 ||
                    (e = tabAt(tab, (n - 1) & h)) == null)
                    return null;
                for (;;) {
                    int eh; K ek;
                    if ((eh = e.hash) == h &&
                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
                        return e;
                    if (eh < 0) {
                        if (e instanceof ForwardingNode) {
                            tab = ((ForwardingNode<K,V>)e).nextTable;
                            continue outer;
                        }
                        else
                            return e.find(h, k);
                    }
                    if ((e = e.next) == null)
                        return null;
                }
            }
        }
    }
	
记录元素个数的节点
@sun.misc.Contended static final class CounterCell {
        volatile long value;
        CounterCell(long x) { value = x; }
    }

7、简单图示

迁移完成后table图示
在这里插入图片描述
迁移前后table的对比

协助扩容线程管理范围图示
在这里插入图片描述

8、ConcurrentHashMap的put方法的流程

1)、判断Node[]数组是否初始化,没有则进行初始化操作
2)、通过hash定位数组的索引坐标,是否有Node节点,如果没有则使用cas进行添加(链表的头节点),添加失败则进入下次循环
3)、检查到内部正在扩容,则协助扩容
4)、如果f!=null,则使用synchronized锁住f元素(链表头节点/红黑树根节点)
如果是Node,则执行链表添加操作
如果是TreeNode,则执行树的添加操作
5)、判断链表长度是否达到临界值8,当节点数超过这个值,需要把链表转化为红黑树(如果Node数组的长度小于64,则进行扩容,不转化红黑树)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值