容器 - ConcurrentHashMap爲何不支持null鍵和null值 原

ConcurrentHashMap爲何不支持null鍵和null值

背景

最近在梳理總結《集合 - 常用Map之間區別》, 其中有一點就是 HashMap 是支持null鍵和null值,而 ConcurrentHashMap 是不支持的;

後來查看了一下jdk源碼,證明了確實是這樣的。

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,正好能解釋我的疑惑。

裏面提到:

ConcurrentHashMap不能put null 是因爲 無法分辨是key沒找到的null還是有key值爲null,這在多線程裏面是模糊不清的,所以壓根就不讓put null。

裏面重點提到一個大師Doug Lea,據說是ConcurrentHashMap的作者,趕緊查看了源碼:

 /**
 * ...
 * 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大師的作品,值得細細品味。

相關資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章