Java Review - 并发组件ConcurrentHashMap使用时的注意事项及源码分析

简介: Java Review - 并发组件ConcurrentHashMap使用时的注意事项及源码分析

195d03d17afc4a928bc581f313b01dfe.png

概述


ConcurrentHashMap虽然为并发安全的组件,但是使用不当仍然会导致程序错误。我们这里通过一个简单的案例来复现这些问题,并给出开发时如何避免的策略。


案例

来个简单的例子,比如有几个注册中心 , 客户端要注册

import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/11/21 10:46
 * @mark: show me the code , change the world
 */
public class ConcurrentHashMapTest {
    // 1 创建Map , key为注册中心地址,value为客户端列表
    private static ConcurrentHashMap<String, List<String>> registMap = new ConcurrentHashMap<>();
    private static final String REGIST_SERVER_A = "注册中心A";
    private static final String REGIST_SERVER_B = "注册中心B";
    public static void main(String[] args) {
        // 2  注册 REGIST_SERVER_A
        Thread threadOne =new Thread(()->{
            List<String> list = new ArrayList<>();
            list.add("客户端一");
            list.add("客户端二");
            registMap.put(REGIST_SERVER_A, list);
            System.out.println( "注册信息:" + JSON.toJSONString(registMap));
        });
        // 3 注册 REGIST_SERVER_A
        Thread threadTwo =new Thread(()->{
            List<String> list = new ArrayList<>();
            list.add("客户端三");
            list.add("客户端四");
            registMap.put(REGIST_SERVER_A, list);
            System.out.println( "注册信息:" + JSON.toJSONString(registMap));
        });
        // 4 注册 REGIST_SERVER_B
        Thread threadThree =new Thread(()->{
            List<String> list = new ArrayList<>();
            list.add("客户端五");
            list.add("客户端六");
            registMap.put(REGIST_SERVER_B, list);
            System.out.println("注册信息:" + JSON.toJSONString(registMap));
        });
        // 5 启动注册
        threadOne.start();
        threadTwo.start();
        threadThree.start();
    }
}


代码(1)创建了一个并发map,用来存放册中心地址及与其对应的客户端列表。

代码(2)和代码(3)模拟客户端注册REGIST_SERVER_A,代码(4)模拟客户端注册REGIST_SERVER_B。

代码(5)启动线程。

运行代码,输出结果如下

6487a766ebbe4735a94e66a8406f8ce8.png

或者


8e44cfc3a9ce4511b411da71da494143.png

886324e4664f42c38d705a7370a7e498.png


原因分析


可见,REGIST_SERVER_A中的客户端会丢失一部分,这是因为put方法如果发现map里面存在这个key,则使用value覆盖该key对应的老的value值。

  /**
     * Maps the specified key to the specified value in this table.
     * Neither the key nor the value can be null.
     *
     * <p>The value can be retrieved by calling the {@code get} method
     * with a key that is equal to the original key.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}
     * @throws NullPointerException if the specified key or value is null
     */
    public V put(K key, V value) {
        return putVal(key, value, false);
    }
    /** 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;
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            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;
                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;
                                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;
    }

而putIfAbsent方法则是,如果发现已经存在该key则返回该key对应的value,但并不进行覆盖,如果不存在则新增该key,并且判断和写入是原子性操作。

   /**
     * {@inheritDoc}
     *
     * @return the previous value associated with the specified key,
     *         or {@code null} if there was no mapping for the key
     * @throws NullPointerException if the specified key or value is null
     */
    public V putIfAbsent(K key, V value) {
        return putVal(key, value, true);
    }


第三个参数 putIfAbsent为true。


修复


使用putIfAbsent替代put方法后的代码如下。


b30ee72ed2044bac81b84d6df41f3bcf.png


import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/11/21 10:46
 * @mark: show me the code , change the world
 */
public class ConcurrentHashMapTest2 {
    // 1 创建Map , key为注册中心地址,value为客户端列表
    private static ConcurrentHashMap<String, List<String>> registMap = new ConcurrentHashMap<>();
    private static final String REGIST_SERVER_A = "注册中心A";
    private static final String REGIST_SERVER_B = "注册中心B";
    public static void main(String[] args) {
        // 2  注册 REGIST_SERVER_A
        Thread threadOne =new Thread(()->{
            List<String> list = new ArrayList<>();
            list.add("客户端一");
            list.add("客户端二");
            // 若果原集合不为空,则追加新的集合
            List<String> oldList = registMap.putIfAbsent(REGIST_SERVER_A, list);
            if (null != oldList){
                oldList.addAll(list);
            }
            System.out.println( "注册信息:" + JSON.toJSONString(registMap));
        });
        // 3 注册 REGIST_SERVER_A
        Thread threadTwo =new Thread(()->{
            List<String> list = new ArrayList<>();
            list.add("客户端三");
            list.add("客户端四");
            List<String> oldList = registMap.putIfAbsent(REGIST_SERVER_A, list);
            // 若果原集合不为空,则追加新的集合
            if (!CollectionUtils.isEmpty(oldList)){
                oldList.addAll(list);
            }
            System.out.println( "注册信息:" + JSON.toJSONString(registMap));
        });
        // 4 注册 REGIST_SERVER_B
        Thread threadThree =new Thread(()->{
            List<String> list = new ArrayList<>();
            list.add("客户端五");
            list.add("客户端六");
            List<String> oldList = registMap.putIfAbsent(REGIST_SERVER_B, list);
            if (!CollectionUtils.isEmpty(oldList)){
                oldList.addAll(list);
            }
            System.out.println("注册信息:" + JSON.toJSONString(registMap));
        });
        // 5 启动注册
        threadOne.start();
        threadTwo.start();
        threadThree.start();
    }
}


使用map.putIfAbsent方法添加新终端列表,如果REGIST_SERVER_A在map中不存在,则将REGIST_SERVER_A和对应终端列表放入map。


要注意的是,这个判断和放入是原子性操作,放入后会返回null。如果REGIST_SERVER_A已经在map里面存在,则调用putIfAbsent会返回REGIST_SERVER_A对应的终端列表,若发现返回的终端列表不为null则把新的终端列表添加到返回的设备列表里面,从而问题得到解决。

e92ad9b022c1456aa8a107b1d7d72e2c.png


小结


put(K key, V value) 方法判断如果key已经存在,则使用value覆盖原来的值并返回原来的值,如果不存在则把value放入并返回null。


而putIfAbsent(K key, V value)方法则是如果key已经存在则直接返回原来对应的值并不使用value覆盖,如果key不存在则放入value并返回null,


另外要注意,判断key是否存在和放入是原子性操作。

相关文章
|
8天前
|
Java
【编程进阶知识】揭秘Java多线程:并发与顺序编程的奥秘
本文介绍了Java多线程编程的基础,通过对比顺序执行和并发执行的方式,展示了如何使用`run`方法和`start`方法来控制线程的执行模式。文章通过具体示例详细解析了两者的异同及应用场景,帮助读者更好地理解和运用多线程技术。
21 1
|
9天前
|
Java
Java基础之 JDK8 HashMap 源码分析(中间写出与JDK7的区别)
这篇文章详细分析了Java中HashMap的源码,包括JDK8与JDK7的区别、构造函数、put和get方法的实现,以及位运算法的应用,并讨论了JDK8中的优化,如链表转红黑树的阈值和扩容机制。
13 1
|
1月前
|
Java
java基础(4)public class 和class的区别及注意事项
本文讲解了Java中`public class`与`class`的区别和注意事项。一个Java源文件中只能有一个`public class`,并且`public class`的类名必须与文件名相同。此外,可以有多个非`public`类。每个类都可以包含一个`main`方法,作为程序的入口点。文章还强调了编译Java文件生成`.class`文件的过程,以及如何使用`java`命令运行编译后的类。
25 3
java基础(4)public class 和class的区别及注意事项
|
19天前
|
JSON Java 开发工具
Java服务端集成Google FCM推送的注意事项和实际经验
公司的app要上海外,涉及到推送功能,经过综合考虑,选择Google FCM进行消息推送。 查看一些集成博客和官方文档,看的似懂非懂,迷迷惑惑。本篇文章除了将我实际集成的经验分享出来,也会对看到的博客及其中产生的疑惑、注意事项一一评论。 从官方文档和众多博客中,你会发现Java集成FCM推送有多种实现方式,会让生产生文档很乱,不知作何选择的困惑。
46 0
|
1月前
|
Java API 容器
JAVA并发编程系列(10)Condition条件队列-并发协作者
本文通过一线大厂面试真题,模拟消费者-生产者的场景,通过简洁的代码演示,帮助读者快速理解并复用。文章还详细解释了Condition与Object.wait()、notify()的区别,并探讨了Condition的核心原理及其实现机制。
|
2月前
|
存储 Java
Java 中 ConcurrentHashMap 的并发级别
【8月更文挑战第22天】
48 5
|
2月前
|
缓存 Java 调度
【Java 并发秘籍】线程池大作战:揭秘 JDK 中的线程池家族!
【8月更文挑战第24天】Java的并发库提供多种线程池以应对不同的多线程编程需求。本文通过实例介绍了四种主要线程池:固定大小线程池、可缓存线程池、单一线程线程池及定时任务线程池。固定大小线程池通过预设线程数管理任务队列;可缓存线程池能根据需要动态调整线程数量;单一线程线程池确保任务顺序执行;定时任务线程池支持周期性或延时任务调度。了解并正确选用这些线程池有助于提高程序效率和资源利用率。
49 2
|
机器学习/深度学习 Java 程序员
Java Review(三十二、异常处理)
Java Review(三十二、异常处理)
131 0
Java Review(三十二、异常处理)
|
XML 存储 Java
Java Review(三十三、异常处理----补充:断言、日志、调试)
Java Review(三十三、异常处理----补充:断言、日志、调试)
171 0
|
4天前
|
安全 Java UED
Java中的多线程编程:从基础到实践
本文深入探讨了Java中的多线程编程,包括线程的创建、生命周期管理以及同步机制。通过实例展示了如何使用Thread类和Runnable接口来创建线程,讨论了线程安全问题及解决策略,如使用synchronized关键字和ReentrantLock类。文章还涵盖了线程间通信的方式,包括wait()、notify()和notifyAll()方法,以及如何避免死锁。此外,还介绍了高级并发工具如CountDownLatch和CyclicBarrier的使用方法。通过综合运用这些技术,可以有效提高多线程程序的性能和可靠性。