关于concurrenthashmap 的 key 和 value不能为空的解释

在学习源码的时候,看到了concurrenthashmap中的value不能为空的情况,突然觉得很奇怪

    public V put(K key, V value) {
        return putVal(key, value, false);
    }

    /** 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;
        // 省略

在Stack Overflow上搜索下回答,其中这段据说是作者 Doug Lea 本人的回答

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.

大概意思就是,null会容易造成混淆,你没法知道get到的一个null,是因为没有这个key,还是本身值就是null,并且在并发环境下的contain是有可能出现改变的,所以就禁止存放null

posted @ 2022-11-07 16:04  myCodeLikeShit  阅读(179)  评论(0编辑  收藏  举报