ConcurrentMaps不允许key、value为null
阅读源码可以发现,HashMap允许插入key和value是null的数据的,而ConcurrentHashMap是不允许key和value是null的。这个是为什么呢?ConcurrentHashMap的作者是这么说的:
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使用map.get(key)时返回为null,无法判断key是不存在还是值为空,non-concurrent还可以再调用map.contains(key)检查,但ConcurrentMaps可能再两次调用间已经发生改变。