| ลำดับ | หัวข้อ | Fail-Fast | Fail-Safe |
|---|
| 1 | ข้อยกเว้น (Exception) | การเปลี่ยนแปลงในคอลเลกชัน เช่น เพิ่ม ลบ อัปเดตขณะ thread กำลังวนรอบ (iterate) Fail-fast จะโยน ConcurrentModificationException | Fail-safe collection ไม่โยนข้อยกเว้น |
| 2 | ประเภทคอลเลกชัน | ArrayList และ HashMap เป็นตัวอย่างของ fail-fast iterator | CopyOnWriteArrayList และ ConcurrentHashMap เป็นตัวอย่างของ fail-safe iterator |
| 3 | ประสิทธิภาพและหน่วยความจำ | ทำงานบนคอลเลกชันจริง ไม่ต้องการหน่วยความจำและเวลาเพิ่มเติม | ทำงานบนโคลนของคอลเลกชัน ไม่ใช่คอลเลกชันจริง มีโอเวอร์เฮดด้านเวลาและหน่วยความจำ |
| 4 | การแก้ไข | Iterator ไม่อนุญาตให้แก้ไขคอลเลกชันขณะวนรอบ | Fail-Safe iterator อนุญาตให้แก้ไขคอลเลกชันขณะวนรอบได้ |
ตัวอย่าง Fail-Safe
public class FailSafeExample{
public static void main(String[] args){
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
// เพิ่มองค์ประกอบใน map
map.put("Dell", 1);
map.put("IBM", 2);
// ได้ Iterator จาก map
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()){
String key = (String) it.next();
System.out.println(key + " : " + map.get(key));
map.put("Google", 3);
}
}
}ผลลัพธ์
IBM :2
Dell:1
ตัวอย่าง Fail-Fast
public class FailFastExample{
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
// ได้ Iterator จาก list
Iterator<Integer> it = list.iterator();
while (it.hasNext()){
Integer integer = (Integer) it.next();
list.add(4);
}
}
}ผลลัพธ์
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)