How do HashMap, Hashtable and ConcurrentHashMap differ in Java?
There are three of them, and they were built at different times for different reasons.
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
Map<String, String> hashMap = new HashMap<String, String>();
Map<String, String> hashtable = new Hashtable<String, String>();
Map<String, String> concurrent = new ConcurrentHashMap<String, String>();
hashMap.put("key", "value");
concurrent.put("key", "value");
// Only the hash map allows a null key and null values.
hashMap.put(null, "a null key");
hashMap.put("a null value", null);
System.out.println("hash map : " + hashMap.size());
System.out.println("hashtable : " + hashtable.size());
System.out.println("concurrent : " + concurrent.size());
}
}
Here are the differences.
HashMap is the ordinary one. It is not safe to use from more than one thread. It allows one null key and any number of null values. It is the one you want in a single threaded program.
Hashtable is the old one. Every one of its methods is synchronised, so it is safe to use from several threads but everything is slow because of the locking. It allows no null keys and no null values at all. It is kept in the language only so that old code keeps working, and new code should not use it.
ConcurrentHashMap is the modern answer. It is safe to use from several threads and it is fast, because it does not lock the whole map for every operation. It allows no null keys and no null values, because a null is a natural signal that something is missing and the map cannot act on that in a thread safe way.
The next question in this topic looks at what the concurrent map actually promises.