HashTable vs ConcurrentHashMap
HashTable (Legacy, JDK 1.1)
- Thread-safe legacy class
- Synchronized ทั้ง collection (coarse-grained lock)
- ไม่ allow null keys/values
- ไม่ maintain order
- Slower เนื่องจาก lock ทั้ง structure
ConcurrentHashMap (JDK 1.5+)
- Lock เฉพาะ bucket level (segment/fragment) - fine-grained locking
- Allow concurrent reads และ writes
- Allow null keys/values (ขึ้นอยู่กับ implementation)
- Better performance สำหรับ high concurrency
ตารางเปรียบเทียบ
| Key | HashTable | ConcurrentHashMap |
|---|---|---|
| Basic | Thread-safe legacy (JDK 1.1) | Introduced in JDK 1.5 |
| Locking | Lock entire collection | Lock at bucket level (fragment) |
| Performance | Slower | Better (high concurrency) |
| Null Keys/Values | Not allowed | Allowed (implementation dependent) |
ตัวอย่าง Hashtable
Hashtable map = new Hashtable();
map.put("HCL", "100");
map.put("DELL", "200");
map.put("IBM", "300");
ตัวอย่าง ConcurrentHashMap
Map myMap = new ConcurrentHashMap();
myMap.put("HCL", "1");
myMap.put("DELL", "1");
สรุป
ConcurrentHashMap เหมาะกว่าสำหรับ high-concurrency environments เนื่องจาก fine-grained locking ให้ throughput สูงกว่า Hashtable มาก