ConcurrentHashMap 源码分析06之函数篇 移除方法详解

1. remove

  • 移除 key 元素对应的节点
/* 两个重载函数,区别在于是否指定元素的value值,底层都是调用 replaceNode */
public V remove(Object key) {
    return replaceNode(key, null, null);
}
public boolean remove(Object key, Object value) {
    if(key == null)
        throw new NullPointerException();
    return value != null && replaceNode(key, null, value) != null;
}

/* value: 替换的值,为null即删除, cv:指定key的旧值,不指定为null,指定需新旧值相等才删除 */
final V replaceNode(Object key, V value, Object cv) {
    int hash = spread(key.hashCode()); // 获取 hash 值
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        /* tab没有元素,直接退出 */
        if (tab == null || (n = tab.length) == 0 ||
            (f = tabAt(tab, i = (n - 1) & hash)) == null)
            break;
        /* 正在扩容,帮助扩容获取新数组 */    
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            boolean validated = false;
            synchronized (f) {
            	/* 判断当前桶位首节点有没有被更改 */
                if (tabAt(tab, i) == f) {
                	/* 链表节点 */
                    if (fh >= 0) {
                        validated = true;
                        for (Node<K,V> e = f, pred = null;;) {
                            K ek;
                            /* 找到节点 */
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                V ev = e.val;
                                /* 不指定旧值 || 新旧值相等,进行替换 or 删除 */
                                if (cv == null || cv == ev ||
                                    (ev != null && cv.equals(ev))) {
                                    oldVal = ev;
                                    /* 替换和删除用的同一方法,使用 value进行区分 */
                                    if (value != null)
                                        e.val = value;
                                    else if (pred != null)
                                        pred.next = e.next;
                                    else
                                        setTabAt(tab, i, e.next);
                                }
                                break;
                            }
                            pred = e;
                            if ((e = e.next) == null)
                                break;
                        }
                    }
                    /* 树节点 */
                    else if (f instanceof TreeBin) {
                        validated = true;
                        TreeBin<K,V> t = (TreeBin<K,V>)f;
                        TreeNode<K,V> r, p;
                        /* 根节点出发,寻找对应的节点 */
                        if ((r = t.root) != null &&
                            (p = r.findTreeNode(hash, key, null)) != null) {
                            V pv = p.val;
                            if (cv == null || cv == pv ||
                                (pv != null && cv.equals(pv))) {
                                oldVal = pv;
                                /* 替换和删除用的同一方法,使用 value 进行区分 */
                                if (value != null)
                                    p.val = value;
                                else if (t.removeTreeNode(p))
                                    setTabAt(tab, i, untreeify(t.first));
                            }
                        }
                    }
                }
            }
            /* validated为true代表进入过节点查找 */
            if (validated) {
            	/* oldVal 不为null即有对应的节点,value不为null是删除,为null是替换,都返回旧值oldVal */
                if (oldVal != null) {
                    if (value == null)
                        addCount(-1L, -1); // 删除节点添加个数为-1,可回看04篇
                    return oldVal;
                }
                break;
            }
        }
    }
    return null;
}

2. clear()

  • 清空当前 concurrentHashMap
public void clear() {
    long delta = 0L; // 记录应该删除的元素数量,记录为负数,调用addCount()
    int i = 0;
    Node<K,V>[] tab = table;
    /* tab 不为null && tab 数组的长度 > 0,循环获取每个桶位首元素 */
    while (tab != null && i < tab.length) {
        int fh;
        Node<K,V> f = tabAt(tab, i);
        /* 首元素为空,无需操作 */
        if (f == null)
            ++i;
        /* tab正在扩容,帮助扩容后获取新数组,重新开始遍历 */    
        else if ((fh = f.hash) == MOVED) {
            tab = helpTransfer(tab, f);
            i = 0; // restart
        }
        else {
        	/* 锁住首节点 */
            synchronized (f) {
            	/* 判断有没有被其他线程修改 */
                if (tabAt(tab, i) == f) {
                	/* 判断是 链表节点 or 树节点 or null */
                    Node<K,V> p = (fh >= 0 ? f :
                                   (f instanceof TreeBin) ?
                                   ((TreeBin<K,V>)f).first : null);
                    /* 循环计数 */
                    while (p != null) {
                        --delta;
                        p = p.next;
                    }
                    setTabAt(tab, i++, null); // 设置桶位元素为null
                }
            }
        }
    }
    /* 若 delta 为0,则当前 map 没有元素 */
    if (delta != 0L)
        addCount(delta, -1);
}

3. replace()

  • 俩重载函数,区别在于是否需要指定旧值,底层调用 replaceNode()
/* 不需要指定旧值,找到就替换,返回旧值,否则返回 null */
public V replace(K key, V value) {
    if (key == null || value == null)
        throw new NullPointerException();
    return replaceNode(key, value, null);
}
/* 指定旧值,找到比较value值,相等替换,返回 boolean 值 */
public boolean replace(K key, V oldValue, V newValue) {
    if (key == null || oldValue == null || newValue == null)
        throw new NullPointerException();
    return replaceNode(key, newValue, oldValue) != null;
}

4. replaceAll

  • 批量替换节点的值
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
	/* null 异常检测 */
    if (function == null) throw new NullPointerException();
    Node<K,V>[] t;
    /* 数组为null,无操作空间 */
    if ((t = table) != null) {
    	/* 获取迭代器 */
        Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
        /* 遍历所有元素,advance() 相当于 next() */
        for (Node<K,V> p; (p = it.advance()) != null; ) {
            V oldValue = p.val;
            /* 这里双层循环是因为防止当前遍历的元素被修改 */
            for (K key = p.key;;) {
                V newValue = function.apply(key, oldValue);
                if (newValue == null)
                    throw new NullPointerException();
                /* replaceNode 返回null有两种可能,要么被删除,要么value被修改
                 * 被修改的情况,使用get()获取新的值,被删除的情况,get()获取为null,break退出 */    
                if (replaceNode(key, newValue, oldValue) != null ||
                    (oldValue = get(key)) == null)
                    break;
            }
        }
    }
}

5. 小总结

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapTest02 {
    public static void main(String[] args) throws Exception {
        ConcurrentHashMap<Integer, Integer> concurrentHashMap = new ConcurrentHashMap<>();
        for(int i = 1; i <= 10; i++) {
            concurrentHashMap.put(i, i);
        }
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.remove(1): " + concurrentHashMap.remove(1));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.remove(11): " + concurrentHashMap.remove(11));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.remove(11): " + concurrentHashMap.remove(2,2));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.remove(11): " + concurrentHashMap.remove(3, 33));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);

        System.out.println("concurrentHashMap.replace(4, 40): " + concurrentHashMap.replace(4, 40));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.replace(40, 40): " + concurrentHashMap.replace(40, 40));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.replace(5, 5, 50): " + concurrentHashMap.replace(5, 5, 50));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);
        System.out.println("concurrentHashMap.replace(6, 60, 60): " + concurrentHashMap.replace(6, 60, 60));
        System.out.println("now concurrentHashMap: " + concurrentHashMap);

        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("============ 这里新添加了元素 ===========");
            for(int i = 11; i <= 23; i++) {
                concurrentHashMap.put(i, i);
            }
        }).start();
        System.out.print("被 replaceAll() 执行的元素: ");
        concurrentHashMap.replaceAll((key, value) -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.print(key + " = " + value + "\t");
            return value * 10;
        });
        System.out.println();
        System.out.println("concurrentHashMap.replaceAll((key, value) -> value * 10 )后, now concurrentHashMap: " + concurrentHashMap);

        concurrentHashMap.clear();
        System.out.println("concurrentHashMap.clear()后, now concurrentHashMap: \n" + concurrentHashMap);

    }
}

  • 可以看到,在进行 replaceAll() 执行替换时,新添加的元素中,[index, tab.length) 位置的元素进行了替换,具体可回看 内部类Traverser 的 advance()方法。(02篇)
    在这里插入图片描述
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ConcurrentHashMapJava 并发包中的一个线程安全的哈希表实现。它采用了分段锁(Segment)的机制来提供高并发性能。下面是简要的 ConcurrentHashMap源码分析ConcurrentHashMap 的整体结构是由多个 Segment 组成的,每个 Segment 内部都是一个 HashEntry 数组,每个数组元素都是一个链表的头节点。每个 Segment 都维护着自己的锁,这样不同的线程可以同时操作不同的 Segment。 在 ConcurrentHashMap 中,关键方法 put、get、remove 等都是通过计算键的哈希值得到对应的 Segment,然后进行对应的操作。这样多个线程可以并行地对不同的 Segment 进行操作,从而提高了并发性能。 ConcurrentHashMap 的 put 方法首先根据 key 的哈希值定位到对应的 Segment,然后使用锁来保证线程安全。如果键已经存在,则会替换对应的值;如果键不存在,则会创建新的节点并添加到链表中。 ConcurrentHashMap 的 get 方法也是根据 key 的哈希值定位到对应的 Segment,然后通过遍历链表来找到对应的节点,并返回节点中的值。 ConcurrentHashMapremove 方法同样也是根据 key 的哈希值定位到对应的 Segment,然后通过遍历链表来找到对应的节点,并将节点从链表中移除。 需要注意的是,在进行扩容操作时,ConcurrentHashMap 会创建新的 Segment 数组,并将每个 Segment 中的元素重新散列到新的数组中。 总之,ConcurrentHashMap 通过使用分段锁的方式来提供高并发性能,同时保证线程安全。每个 Segment 内部是一个独立的哈希表,对不同的 Segment 可以进行并发操作。这使得 ConcurrentHashMap 成为了高效的并发哈希表实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值