ConcurrentHashMap là class giới thiệu trong JDK 1.5. ConcurrentHashMap áp dụng lock chỉ ở bucket level (fragment) khi thêm hoặc cập nhật map. Do đó, ConcurrentHashMap cho phép đọc và ghi đồng thời (concurrent read and write).
HashTable là class legacy thread-safe giới thiệu trong JDK 1.1. Là triển khai cơ bản của Map interface. Không cho phép null keys và values. Bản chất synchronized nên hai luồng khác nhau không thể truy cập cùng lúc. Hashtable không duy trì thứ tự nào.
| STT | Tiêu chí | HashTable | ConcurrentHashMap |
|---|---|---|---|
| 1 | Cơ bản | Thread-safe legacy class từ JDK 1.1 | Class từ JDK 1.5, lock ở bucket level |
| 2 | Locking | Lock toàn bộ collection | Lock chỉ ở bucket level (fragment) khi add/update |
| 3 | Performance | Chậm hơn ConcurrentHashMap | Tốt hơn HashTable |
| 4 | Null key/value | Không cho phép null key và value | Cho phép null key và value |
Ví dụ Hashtable
import java.util.Hashtable;
import java.util.Map;
public class HashtableExample {
public static void main(String[] args) {
Hashtable map = new Hashtable();
map.put("HCL", "100");
map.put("DELL", "200");
map.put("IBM", "300");
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Ví dụ ConcurrentHashMap
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
Map myMap = new ConcurrentHashMap();
myMap.put("HCL", "1");
myMap.put("DELL", "1");
for (Map.Entry m : myMap.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}