What is the difference between HashMap, Hashtable and ConcurrentHashMap?

PointHashMapHashtableConcurrentHashMap
Thread safeNoYes (locks the whole table)Yes (fine grained locks)
Null keyOne allowedNot allowedNot allowed
Null valuesAllowedNot allowedNot allowed
SpeedFastest (one thread)SlowFast with many threads
UseNormal codeOld code onlyShared data between threads
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    static void tryNull(String name, Map<String, String> map) {
        try {
            map.put(null, "x");
            System.out.println(name + ": null key allowed");
        } catch (NullPointerException e) {
            System.out.println(name + ": null key NOT allowed");
        }
    }

    public static void main(String[] args) {
        tryNull("HashMap", new HashMap<>());
        tryNull("Hashtable", new Hashtable<>());
        tryNull("ConcurrentHashMap", new ConcurrentHashMap<>());
    }
}
Output

HashMap: null key allowed
Hashtable: null key NOT allowed
ConcurrentHashMap: null key NOT allowed


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.