| STT |
Tiêu chí |
Fail-Fast |
Fail-Safe |
| 1 |
Ngoại lệ |
Mọi thay đổi trong collection (thêm, xóa, cập nhật) khi một thread đang lặp qua collection thì Fail-fast ném ConcurrentModificationException. |
Fail-safe collection không ném ngoại lệ. |
| 2 |
Loại collection |
ArrayList và HashMap là ví dụ của fail-fast iterator. |
CopyOnWriteArrayList và ConcurrentHashMap là ví dụ của fail-safe iterator. |
| 3 |
Hiệu năng và bộ nhớ |
Làm việc trên collection thực tế. Do đó iterator này không yêu cầu bộ nhớ và thời gian thêm. |
Làm việc trên bản sao của collection thay vì collection thực tế. Là overhead về thời gian và bộ nhớ. |
| 4 |
Thay đổi |
Iterator không cho phép sửa đổi collection khi đang lặp qua nó. |
Fail-Safe iterator cho phép sửa đổi collection khi đang lặp qua nó. |
Ví dụ Fail-Safe
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
public class FailSafeExample {
public static void main(String[] args) {
ConcurrentHashMap map = new ConcurrentHashMap<>();
// Thêm phần tử vào map
map.put("Dell", 1);
map.put("IBM", 2);
// Lấy Iterator từ map
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key + " : " + map.get(key));
map.put("Google", 3); // Sửa đổi khi đang lặp
}
}
}
Kết quả
IBM : 2
Dell : 1
Ví dụ Fail-Fast
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class FailFastExample {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
// Lấy Iterator từ list
Iterator it = list.iterator();
while (it.hasNext()) {
Integer integer = it.next();
list.add(4); // Sửa đổi khi đang lặp -> ném ConcurrentModificationException
}
}
}
Kết quả
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)