DEMO
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapTest {
public static void main(String[] args) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("1", 1);
hashMap.put("2", 2);
hashMap.put("3", 3);
hashMap.put("4", 4);
hashMap.put("5", null);
final ConcurrentHashMap<Object, Object> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.putAll(hashMap);
}
}
场景复现
今天重构代码,需要将 同步代码改为异步执行,所以将原来的 HashMap
改为线程安全的 ConcurrentHashMap
所以出现了这个问题;
调试的时候出现了 NullPointerException
这个异常,
方向错误
这本来是一个比较常见的异常,但是由于是重构别人的代码(不清楚 Value 可能为null 的情况),和新加了多线程的功能(对于多线程知识掌握的不扎实);所以一直以为是多线程的情况时, hashMap 变量 或 concurrentHashMap 变量会出现null 的情况;
### 发现异常的根因
其实只需要点开被折叠的异常信息,就能发现具体哪儿抛出的异常了;是因为 ConcurrentHashMap
的 value 不能为null, hashMap 是可以的
总结
1、Java 基础 ConcurrentHashMap 和 HashMap 的区别不够了解
2、对于 多线程的知识不够自信(总感觉有雷)
3、对于异常堆栈信息查看不够仔细
求甚解
为啥 ConcurrentHashMap 的 Value 不能为 null?(先挖坑)
#来时坑 #多线程 #ConcurrentHashMap