Interview question
What is the difference between fail-fast and fail-safe iterators in Java? Java में fail-fast और fail-safe iterators में क्या अंतर है?
Answer
| Type | Behavior on modification during iteration | Examples |
|---|---|---|
| Fail-fast | Throws ConcurrentModificationException immediately | ArrayList, HashMap, HashSet iterators |
| Fail-safe | Works on a copy, no exception, but may not reflect the latest changes | CopyOnWriteArrayList, ConcurrentHashMap |
// Fail-fast example - throws exception
List<String> list = new ArrayList<>(Arrays.asList('A', 'B', 'C'));
for (String item : list) {
if (item.equals('B')) {
list.remove(item); // ConcurrentModificationException!
}
}
// Fail-fast iterators use a 'modCount' internally - if it changes
// unexpectedly during iteration, the exception is thrown
// SAFE alternative using Iterator.remove()
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals('B')) {
it.remove(); // safe - the iterator itself tracks this modification
}
}
// Fail-safe example - no exception, but may miss recent updates
List<String> safeList = new CopyOnWriteArrayList<>(Arrays.asList('A', 'B', 'C'));
for (String item : safeList) {
if (item.equals('B')) {
safeList.remove(item); // no exception - operates on a snapshot copy
}
}
System.out.println(safeList); // [A, C]
// ConcurrentHashMap - fail-safe for concurrent read/write scenarios
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put('a', 1);
// safe to modify while another thread iterates, unlike HashMap| Type | Iteration के दौरान modification | उदाहरण |
|---|---|---|
| Fail-fast | तुरंत ConcurrentModificationException | ArrayList, HashMap iterators |
| Fail-safe | Copy पर काम, exception नहीं | CopyOnWriteArrayList, ConcurrentHashMap |
List<String> list = new ArrayList<>(Arrays.asList('A', 'B', 'C'));
for (String item : list) {
if (item.equals('B')) {
list.remove(item); // ConcurrentModificationException!
}
}
// सुरक्षित alternative
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals('B')) {
it.remove(); // सुरक्षित
}
}
// Fail-safe उदाहरण
List<String> safeList = new CopyOnWriteArrayList<>(Arrays.asList('A', 'B', 'C'));
for (String item : safeList) {
if (item.equals('B')) {
safeList.remove(item); // exception नहीं
}
}
System.out.println(safeList); // [A, C]
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put('a', 1);Was this answer clear?