Connor学Java - JDK8中的ConcurrentHashMap是如何保证线程安全的

在这里插入图片描述

Learn && Live

虚度年华浮萍于世,勤学善思至死不渝

前言

Hey,欢迎阅读Connor学Java系列,这个系列记录了我的Java基础知识学习、复盘过程,欢迎各位大佬阅读斧正!原创不易,转载请注明出处:http://t.csdn.cn/h86q2,话不多说我们马上开始!

JDK8中的ConcurrentHashMap是如何保证线程安全的?

实现原理
public class ConcurrentHashMap<K,V> 
    extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable {
    
	// 可用处理器数量
	static final int NCPU = Runtime.getRuntime().availableProcessors();
	
    // 存放node的数组
	transient volatile Node<K,V>[] table;
	
    // 控制标识符
	private transient volatile int sizeCtl;
    
    static class Node<K,V> implements Map.Entry<K,V> {
    	final int hash;
    	final K key;
    	// val和next都会在扩容时发生变化,所以加上volatile来保持可见性和禁止重排序
    	volatile V val;              // get操作全程不需要加锁是因为Node的成员val是用volatile修饰
    	volatile Node<K,V> next;     // 表示链表中的下一个节点,数组用volatile修饰主要是保证在数组扩容的时候保证可见性
    }
}

相比JDK7做了如下修改

(1)取消了Segments,直接采用transient volatile HashEntry<K,V>[] table保存数据,采用table数组元素作为锁,从而实现了对每一行数据进行加锁,并发控制使用Synchronized和CAS来操作

(2)将原先table数组+单向链表的数据结构,变更为table数组+单向链表+红黑树的结构,与HashMap一样,当链表长度大于8且数组长度大于64时,链表将转换为红黑树,相反,若红黑树上的元素个数减少到6时,就会退化为链表

(3)增加控制标识符,用来控制table的初始化和扩容操作

  • 当为负数时,-1代表正在初始化,-n代表有n-1个线程正在扩容
  • 当为0时,代表当前table还没有被初始化
  • 当为正数时,其数值表示初始化或下一次进行扩容的大小,相当于threshold
初始化时的线程安全
public V put(K key, V value) {
    return putVal(key, value, false);
}

final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    // 计算key的hash值
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        // 如果table是空,初始化之
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        ...
    }
    ...
}

private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    // (0)
    while ((tab = table) == null || tab.length == 0) {
        // (1)
        if ((sc = sizeCtl) < 0)
            Thread.yield(); // lost initialization race; just spin
        // 尝试原子性的将指定对象(this)的内存偏移量为SIZECTL的int变量值从sc更新为-1
        // 也就是将成员变量sizeCtl的值改为-1
        // (2)
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
            try {
                // (3)
                if ((tab = table) == null || tab.length == 0) {
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY; // 默认初始容量为16
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    // (4)
                    table = tab = nt; // 创建hash表,并赋值给成员变量table
                    sc = n - (n >>> 2);
                }
            } finally {
                // (5)
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

(1)sizeCtl < 0,说明当前有其他线程,将当前线程变为就绪状态

(2)sizeCtl >= 0,当前线程通过CAS的方式(实现方式见注释,此处不详细介绍)尝试将sizeCtl修改为-1

  • 修改失败,进入下一轮循环,sizeCtl < 0,回到就绪状态继续等待
  • 修改成功,继续执行

(3)双重检验:在new Node[]之前,要再检查一遍table是否为空,因为如果另一个线程执行完代码// (0)后挂起,此时另一个初始化的线程执行完了(5)的代码,此时sizeCtl是一个大于0的值,那么再切回这个线程执行的时候,是有可能重复初始化的。

(4)指定数组容量,重新计算sizeCtl,完成初始化

put方法的线程安全

hash表对应index为空

/** 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;
        // 初始化
        ...
        // hash表对应index为空
        // (1)
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            // (2)
            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);
        // hash表对应index不为空
        else {
            ...
        }
    }
    addCount(1L, binCount);
    return null;
}

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

(1)tabAt方法通过Unsafe.getObjectVolatile()的方式获取数组对应index上的元素,getObjectVolatile作用于对应的内存偏移量上,是具备volatile内存语义的

(2)如果获取的是空,尝试用cas的方式在数组的指定index上创建一个新的Node

hash表对应index不为空(发生散列冲突)

/** 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;
        // 初始化
        ...
        // hash表对应index为空
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
			...
        }
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        // hash表对应index不为空
        else {
            V oldVal = null;
            // (1)
            synchronized (f) {
                // (2)
                if (tabAt(tab, i) == f) {
                    // (3)
                    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;
}

(1)锁f在上述的情况中获取,即发生冲突时,会以链表的头节点作为锁

(2)保证扩容等过程没有对table数组产生影响,导致原来的index上的Node改变,否则之前的f锁将失去意义

(3)确保put没有与扩容同时进行,fh = -1表示正在扩容

上述就是有关保证线程安全的操作,后续put实现参考HashMap,包括链表、红黑树的操作和转换等

transfer扩容的线程安全

在上面put源码分析的最后调用了addCount方法,这个方法用于统计hash表中元素的个数,如果超过了阈值sizeCtl,扩容

transient volatile Node<K,V>[] table;

// 扩容时才使用的hash表,扩容完成后赋值给table,并将nextTable重置为null
private transient volatile Node<K,V>[] nextTable;

private final void addCount(long x, int check) {
    // 计算键值对的个数
    // (1)
    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;
        // (2)
        while (s >= (long)(sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {
            int rs = resizeStamp(n);
            // (2)
            if (sc < 0) {
                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0)
                    break;
                // (2) - 1
                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                    transfer(tab, nt);
            }
            // (2) - 2
            else if (U.compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))
                transfer(tab, null);
            s = sumCount();
        }
    }
}

private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
    int n = tab.length, stride;
    if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
        stride = MIN_TRANSFER_STRIDE;
    // 对应上述(2) - 2的情况
    if (nextTab == null) {
        try {
            @SuppressWarnings("unchecked")
            // 初始化新的hash表,大小为之前的2倍,并赋值给成员变量nextTable
            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
            nextTab = nt;
        } catch (Throwable ex) {
            sizeCtl = Integer.MAX_VALUE;
            return;
        }
        nextTable = nextTab;
        transferIndex = n;
    }
    // (3)
    int nextn = nextTab.length;
    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;
            // (4)
            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;
            }
        }
        else if ((f = tabAt(tab, i)) == null)
            advance = casTabAt(tab, i, null, fwd);
        else if ((fh = f.hash) == MOVED)
            advance = true; // already processed
        else {
            // (5)
            synchronized (f) {
                if (tabAt(tab, i) == f) {
                    Node<K,V> ln, hn;
                    if (fh >= 0) {
                        ...
                    }
                    else if (f instanceof TreeBin) {
                        ...
                    }
                }
            }
        }
    }
}

(1)统计hash表中的键值对个数

(2)若键值对个数的值大于sizeCtl(这里需要注意,结合之间对sizeCtl含义的讨论,只要不是键值对个数小于sizeCtl,都是需要考虑扩容的情况),在根据sizeCtl的正负进行讨论

  • sizeCtl < 0,说明当前有多个进程并发进行扩容操作,调用transfer(tab, nt),直接使用正在扩容的新hash表,保证不会出现被覆盖的情况
  • sizeCtl > 0,此时为没有并发扩容的情况,transfer中会new一个新的hash表来扩容,大小为原来的2倍

(3)完成扩容后hash表中元素的迁移操作

(4)扩容完成时,将成员变量nextTable置为null,并将table替换为rehash后的nextTable

(5)遍历每个链表或红黑树,对每个元素进行rehash操作,将链表头节点或红黑树的根节点作为锁,防止扩容时进行put操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ConnorYan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值