ConcurrentHashMap

jdk 1.8 ConcurrentHashMap

1、数据结构

数组 + 链表 + 红黑树
在这里插入图片描述

2、put 流程图

put 流程图

3、源代码
  • 字段
   
	// 当值为负数时,表示正在初始化数组或者调整大小
    private transient volatile int sizeCtl;
  • put 方法
	public V put(K key, V value) {
        return putVal(key, value, false);
    }
	
	// 计算 hash 值
	static final int spread(int h) {
        return (h ^ (h >>> 16)) & HASH_BITS;
    }
    
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        // 键值都不能为空
        if (key == null || value == null) throw new NullPointerException();
        // 计算 hash 值
        int hash = spread(key.hashCode());
        int binCount = 0;
        // 遍历 node 数组
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            // 数组为空
            if (tab == null || (n = tab.length) == 0)
                // 初始化数组
                tab = initTable();
            // 数组的位置没有数据,使用 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
            }
            // 判断是否需要扩容
            else if ((fh = f.hash) == MOVED)
                // 扩容
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                // 只对当前 node 结点所在的链表/红黑树加锁,提高了效率
                synchronized (f) {
                    // 链表
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            binCount = 1;
                            // 遍历链表
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                // key 值和 hash 值相等,直接修改值
                                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;
                            }
                        }
                    }
                }
                // 结点数大于 8,转换为 红黑树
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        // 扩容
        addCount(1L, binCount);
        return null;
    }
  • initTable
	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;
    }
4、如何保证多线程安全?
  • 使用 synchronized 和 cas 来操作,每次锁的都是当前桶(数组所在的链表或者红黑树),提高了性能
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值