首页 > 其他分享 >关于concurrenthashmap 的 key 和 value不能为空的解释

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

时间:2022-11-07 16:15:07浏览次数:45  
标签:map concurrenthashmap key value 为空 null

在学习源码的时候,看到了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

标签:map,concurrenthashmap,key,value,为空,null
From: https://www.cnblogs.com/westlin/p/16866295.html

相关文章