What is the difference between HashMap, Hashtable and ConcurrentHashMap?
| Point | HashMap | Hashtable | ConcurrentHashMap |
|---|---|---|---|
| Thread safe | No | Yes (locks the whole table) | Yes (fine grained locks) |
| Null key | One allowed | Not allowed | Not allowed |
| Null values | Allowed | Not allowed | Not allowed |
| Speed | Fastest (one thread) | Slow | Fast with many threads |
| Use | Normal code | Old code only | Shared 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 |