为什么ConcurrentHashMap中key不允许为null?(美团)
Doug Lea 是 Java 并发编程领域的知名专家,他曾经是 Java 并发包的主要设计者之一,也是 Java 并发编程的重要贡献者。对于 ConcurrentHashMap 不允许插入 null 值的问题,有人问过 Doug Lea,以下是他回复的邮件内容:
1 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. 2 3 Further digressing: I personally think that allowingnulls in Maps (also Sets) is an open invitation for programsto contain errors that remain undetected untilthey break at just the wrong time. (Whether to allow nulls evenin non-concurrent Maps/Sets is one of the few design issues surroundingCollections that Josh Bloch and I have long disagreed about.) 4 5 It is very difficult to check for null keys and valuesin my entire application .Would it be easier to declare somewherestatic final Object NULL = new Object();and replace all use of nulls in uses of maps with NULL?

所以,为了让ConcurrentHashMap的语义更加准确,不存在二义性的问题,他就不支持null。
希望本文章对您有帮助,您的转发、点赞是我的创作动力,十分感谢。更多好文推荐,请关注我的微信公众号--JustJavaIt