Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง HashTable และ ConcurrentHashMap ใน Java

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

ตารางเปรียบเทียบ

KeyHashTableConcurrentHashMap
BasicThread-safe legacy (JDK 1.1)Introduced in JDK 1.5
LockingLock entire collectionLock at bucket level (fragment)
PerformanceSlowerBetter (high concurrency)
Null Keys/ValuesNot allowedAllowed (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 มาก