HashMap of key and value can be empty, ConcurrentHashMap and HashTable not, why

Scenarios

HashMap is not thread-safe, so under used in single-threaded scenarios
ConcurrentHashMap and HashTable are thread-safe, multithreaded scenarios applied under

The reason for the difference

When calling get (key), if the return value is empty, can determine this value is stored is null null key or because there is no return.

the reason

HashMap

Because the single-threaded application is HashMap scenario, in the source code, when it is determined key is empty, the value stored will table [0] at.
When the value is empty, by ** containsKey (key) ** determines whether a key, if so, then the return value of null is empty, if not the key, then return null the key is not empty .
When the stored key and value are empty, containskey (key) also returns true, that there Node node table (Node attribute of key and value are null)

HashTable和concurrentHashmap

Because the two sets are applied to multithreaded scenarios, during use of the two methods containsKey (key) and GET (key), there may be a key value for other threads to modify, so that, after the return true containsKey (key) another thread will delete key, this time on behalf of the null get (key) return is not the key, but the thread but thought it was value is empty, there is a conflict.

Why put key can not be null, possibly to correspond to the value, since the value can not be null, and the key is null and do not avoid anything unexpected exception.
(Source code like this, did not find any specific reasons, if any, can be made welcome Gangster)

Code

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class TestMap {
    public static void main(String[] args){
        HashMap<Integer,Integer> map = new HashMap<>();
        System.out.println(map.containsKey(null));
        System.out.println(map.get(null));

        map.put(null,null);//当key为空时,key的hash值为0
        System.out.println(map.containsKey(null));
        System.out.println(map.get(null));

        map.put(null,123);
        System.out.println(map.containsKey(null));
        System.out.println(map.get(null));

        ConcurrentHashMap<Integer,Integer> cmap = new ConcurrentHashMap<>();
        System.out.println(cmap.containsKey(null));
        System.out.println(cmap.get(null));

        cmap.put(null,123);
        cmap.put(123,null);

    }
}

Output: From containsKey (key) at the start exception.

false
null
true
null
true
123
Exception in thread “main” java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:964)
at TestMap.main(TestMap.java:21)
Process finished with exit code 1

Published 12 original articles · won praise 0 · Views 192

Guess you like

Origin blog.csdn.net/N_a_n/article/details/105025242