ConcurrentHashMap放入null值报错
//ConcurrentHashMap源码:
/** Implementation for put and putIfAbsent */ final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) throw new NullPointerException(); //......
关于为什么这么设计(stackoverflow上的回答):
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.
也就是说对于能够支持并发修改的ConcurrentMaps,如果取值的时候返回null,你很难判断是本来那个值就是被映射为的null,还是根本就没设置这个key-value对。
本博客文章皆出于学习目的,个人总结或摘抄整理自网络。引用参考部分在文章中都有原文链接,如疏忽未给出请联系本人。另外,作为一名菜鸟程序媛,如文章内容有错误,欢迎点击博客右上方的扣扣链接指导交流。