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对。

posted @ 2018-01-08 15:22  JillWen  阅读(3532)  评论(0编辑  收藏  举报