ConcurrentHashMap เป็นคลาสที่เพิ่มเข้ามาใน JDK 1.5 ใช้การล็อกเฉพาะระดับบัคเก็ต (bucket level) เรียกว่า segment/segment locking ขณะเพิ่มหรืออัปเดตแมพ ทำให้ ConcurrentHashMap รองรับการอ่านและเขียนพร้อมกัน (concurrent read and write)
Synchronized HashMap (Collections.synchronizedMap()) เป็นเมธอดของ Collection framework ใช้ล็อกทั้งแมพ (locks the entire collection) ดังนั้นถ้าเธรดหนึ่งกำลังเข้าถึงแมพ เธรดอื่นจะเข้าถึงแมพเดียวกันไม่ได้
ตารางเปรียบเทียบรายละเอียด
| ลำดับ | หัวข้อ | ConcurrentHashMap | Synchronized HashMap |
|---|---|---|---|
| 1 | การนำไปใช้ | เป็นคลาสที่ implement ConcurrentMap และ Serializable | เป็นเมธอดในคลาส Collections |
| 2 | กลไกล็อก | ล็อกเฉพาะส่วน (segment/bucket level) | ล็อกทั้งแมพ |
| 3 | ประสิทธิภาพ | รองรับ concurrent read/write ดีกว่า | หลายเธรดเข้าถึงไม่ได้พร้อมกัน ประสิทธิภาพต่ำกว่า |
| 4 | Null Key | ไม่รองรับ null เป็น key หรือ value | รองรับ null เป็น key ได้ |
| 5 | ConcurrentModificationException | ไม่โยน ConcurrentModificationException | Iterator ที่คืนค่าจะโยน ConcurrentModificationException |
ตัวอย่าง SynchronizedMap
Map<Integer, String> laptopMap = new HashMap<>();
laptopMap.put(1, "IBM");
laptopMap.put(2, "Dell");
laptopMap.put(3, "HCL");
Map<Integer, String> syncMap = Collections.synchronizedMap(laptopMap);
System.out.println("Synchronized map: " + syncMap);
ตัวอย่าง ConcurrentHashMap
Map<Integer, String> laptopMap = new ConcurrentHashMap<>();
laptopMap.put(1, "IBM");
laptopMap.put(2, "Dell");
laptopMap.put(3, "HCL");
System.out.println("ConcurrentHashMap: " + laptopMap);
สรุป
ConcurrentHashMap เหมาะสำหรับสภาพแวดล้อม multi-thread ที่ต้องการประสิทธิภาพสูงและความปลอดภัยของเธรด (thread-safe) ส่วน Synchronized HashMap ใช้งานง่ายกว่า แต่ประสิทธิภาพต่ำกว่าเมื่อมีเธรดมากเข้าถึงพร้อมกัน