ConcurrentHashmap、HashMap和Hashtable都是key-value存储结构,但他们有一个不同点是 ConcurrentHashmap、Hashtable不支持key或者value为null,而HashMap是支持的

为什么要这么设计?

在网上找到了这样的解答:The main reason that nulls aren’t allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities(歧义) that may be just barely tolerable in non-concurrent maps can’t be accommodated(接纳、容忍). The main one is that if map.get(key) returns null, you can’t detect whether the key explicitly(明确) maps to null vs the key isn’t mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

  当通过get(k)获取对应的value时,如果获取到的是null时,无法判断,它是put(k,v)的时候value为null(进行了映射),还是这个key从来没有做过映射,无法分辨是key没找到的null还是有key值为null。假如线程1调用m.contains(key)返回true,然后在调用m.get(key),这时的m可能已经不同了。因为线程2可能在线程1调用m.contains(key)时,删除了key节点,这样就会导致线程1得到的结果不明确,产生多线程安全问题,因此,Hashmap和ConcurrentHashMap的key和value不能为null。

HashMap允许key和value为null,在单线程时,调用contains()和get()不会出现问题,但是多线程下,就是线程不安全的。

Map<String, JSONObject> keyMap = new HashMap<>();
if (keyMap.containsKey(companyCode)) {
     JSONObject object = keyMap.get(companyCode);
     object.put("num", object.getIntValue("num") + 1);
}

 

posted on 2021-02-22 17:42  周文豪  阅读(442)  评论(0编辑  收藏  举报