Java Collections Framework เป็นพื้นฐานสำคัญที่ทำให้ Java จัดการข้อมูลได้หลากหลายและมีประสิทธิภาพ แต่ collections แบบดั้งเดิม (Traditional Collections) มีข้อจำกัดในสภาพแวดล้อม multi-threading จึงมี Concurrent Collections เข้ามาแก้ปัญหา
Traditional Collections (Legacy Collections)
Class หลัก: ArrayList, LinkedList, HashMap, HashSet, TreeMap, TreeSet เป็นต้น
- Non-synchronized - ไม่ปลอดภัยต่อ thread
- มีบาง class synchronized แบบเก่า:
Vector,Stack,Hashtable- ใช้ lock ทั้ง object (coarse-grained locking) - Iterator เป็น fail-fast - โยน
ConcurrentModificationExceptionหาก collection ถูก modify ระหว่าง iterate
Concurrent Collections (java.util.concurrent)
นำเสนอใน JDK 1.5 ปรับปรุงต่อเนื่องจนถึงปัจจุบัน Class หลัก:
- ConcurrentHashMap - แทน Hashtable / synchronized HashMap
- CopyOnWriteArrayList - แทน synchronized ArrayList (เหมาะ read-heavy)
- CopyOnWriteArraySet
- ConcurrentLinkedQueue, ConcurrentLinkedDeque
- BlockingQueue implementations:
ArrayBlockingQueue,LinkedBlockingQueue,PriorityBlockingQueue,DelayQueue,SynchronousQueue - ConcurrentSkipListMap, ConcurrentSkipListSet - sorted concurrent collections
ตารางเปรียบเทียบ
| ลำดับ | หัวข้อ | Traditional Collections | Concurrent Collections |
|---|---|---|---|
| 1 | Thread Safety | ส่วนใหญ่ non-synchronized (Vector, Hashtable synchronized แบบ coarse-grained) | ออกแบบมาเป็น thread-safe ตั้งแต่ต้น (fine-grained / lock-free) |
| 2 | Locking Mechanism | Coarse-grained: lock ทั้ง collection (Vector, Hashtable) | Fine-grained / Lock-free: lock แค่ส่วนที่จำเป็น (segment/bucket) หรือใช้ CAS |
| 3 | Iterator Behavior | Fail-fast: โยน ConcurrentModificationException | Weakly consistent: ไม่โยน exception, แสดง snapshot ณ ขณะนั้น |
| 4 | Modification during Iteration | ไม่ได้ (โยน exception) | ได้ (weakly consistent iterator) |
| 5 | Performance (Multi-thread) | ต่ำมาก หาก wrap synchronized | สูงมาก รองรับ concurrency เริ่มต้น |
| 6 | นำเสนอ | JDK 1.2 (Collections Framework) | JDK 1.5 (java.util.concurrent package) |
เมื่อไหร่ควรใช้ Concurrent Collections?
- หลาย thread เข้าถึง collection พร้อมกัน (read/write)
- ต้องการ throughput สูงใน multi-threaded environment
- Producer-Consumer patterns (ใช้ BlockingQueue)
- Caching, Session management, Counters, Registries
ข้อควรระวัง
- Concurrent collections มี overhead สูงกว่าใน single-thread - อย่าใช้โดยไม่จำเป็น
- Iterator เป็น weakly consistent - อาจไม่เห็นการเปลี่ยนแปลงล่าสุด
- Compound actions (เช่น check-then-act) ยังต้อง synchronize เองถ้าต้องการ atomicity