小言_互联网的博客

关于HashMap和ConcurrentHashMap NullPointerException的问题

351人阅读  评论(0)

文章目录


背景

之前工作中对代码进行重构,发现之前的全是用的HashMap,HashMap是线程不安全的,所以想到用ConcurrentHashMap,简单说是一个分段的HashTable,使得在加锁的基础上,效率默认提升了16倍。

可是用了ConcurrentHashMap后,原来不报错的地方突然报错了,晕~

具体代码就不贴图了,就是比较常见的空指针异常。

Demo

public class Test {
	public static void main(String[] args) {
		Map<String, String> hashMap = new HashMap<String, String>();
		String s = hashMap.get(null);
		System.out.println("HashMap get --- "+s);
		hashMap.put(null, null);
		System.out.println("HashMap put success !");

		ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<String, String>();
		String s1 = concurrentHashMap.get(null);
		System.out.println("ConcurrentHashMap---"+concurrentHashMap);
		concurrentHashMap.put(null, null);
		System.out.println("concurrentHashMap put success !");
	}
}


可以看到HashMap 支持 null key、null value , ConcurrentHashMap不支持 null key、null value 。

ConcurrentHashMap :
put方法,key/value 如果为null 直接抛出异常。
get方法,key没有判断null 会报空指针异常

总结

HashMap

  static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

ConcurrenHashMap

/** 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;
     ......
}

上面是源码层面,可是为什么这样设计?

ConcurrentHashmap HashMap和Hashtable都是key-value存储结构,但他们有一个不同点是 ConcurrentHashmap、Hashtable不支持key或者value为null,而HashMap是支持的。为什么会有这个区别?在设计上的目的是什么?
ConcurrentHashmap和Hashtable都是支持并发的,这样会有一个问题,当你通过get(k)获取对应的value时,如果获取到的是null时,你无法判断,它是put(k,v)的时候value为null,还是这个key从来没有做过映射。HashMap是非并发的,可以通过contains(key)来做这个判断。而支持并发的Map在调用m.contains(key)和m.get(key),m可能已经不同了。
—https://www.cnblogs.com/heqiyoujing/p/10928334.html

ConcurrentHashMap不能put null 是因为 无法分辨是key没找到的null还是有key值为null,这在多线程里面是模糊不清的,所以压根就不让put null。
—https://blog.csdn.net/u013837825/article/details/87743520


转载:https://blog.csdn.net/dataiyangu/article/details/101537451
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场