zoukankan      html  css  js  c++  java
  • 为什么ConcurrentHashMap,HashTable不支持key,value为null?

    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);
    }
  • 相关阅读:
    java1234初学maven
    解决maven创建web项目卡死在generator插件(转)
    maven下载速度慢的解决方法(转)
    git分支
    git基础
    oracle分析函数与over()(转)
    Oracle开窗函数 over()(转)
    Oracle计算时间函数(对时间的加减numtodsinterval、numtoyminterval) (转)
    selenium使用中遇到的问题
    selenium运行火狐报错FirefoxDriver : Unable to connect to host 127.0.0.1 on port 7055
  • 原文地址:https://www.cnblogs.com/zwh0910/p/14354332.html
Copyright © 2011-2022 走看看