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
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?