容器 - ConcurrentHashMap为什么不支持null键和null值

ConcurrentHashMap为什么不支持null键和null值

背景

最近在梳理总结《集合 - 经常使用Map之间区别》, 其中有一点就是 HashMap 是支持null键和null值,而 ConcurrentHashMap 是不支持的;html

后来查看了一下jdk源码,证实了确实是这样的。java

HashMap.java 部分源码编程

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

ConcurrentHashMap.java 部分源码多线程

/** 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;
        ......
    }

知其然不知其因此然

后来,当有人问起我为何ConcurrentHashMap不支持null key value时,我却只能说源码里就那么写的,殊不知为什么!并发

知其因此然

上网google了一下,发现一片很不错的文章关于ConcurrentHashMap为何不能put null,正好能解释个人疑惑。app

里面提到:框架

ConcurrentHashMap不能put null 是由于 没法分辨是key没找到的null仍是有key值为null,这在多线程里面是模糊不清的,因此压根就不让put null。

里面重点提到一个大师Doug Lea,听说是ConcurrentHashMap的做者,赶忙查看了源码:this

/**
 * ...
 * Java Collections Framework</a>.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 */
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable {
    private static final long serialVersionUID = 7249069246763182397L;
    ...
}

原来整个java.util.concurrent大多都是Lea大师的做品,值得细细品味。google

相关资料

相关文章
相关标签/搜索