Fail Fast Iterator vs Fail Safe Iterator in Java
This post will discuss the fail-fast iterator and fail-safe iterator in Java.
Fail Fast Iterator in Java
If a thread modifies the collection’s structure, i.e., add elements to it or remove elements from it, while another thread (or same thread) is iterating over it, ConcurrentModificationException may be thrown by the iterator. Iterator implementations that throw ConcurrentModificationException are known as fail-fast iterators, as they fail quickly and cleanly, rather than risking arbitrary, non-deterministic behavior later.
For example, the following methods will throw a ConcurrentModificationException as they permit concurrent modification on an ArrayList instance:
1. Using an iterator
The iterators returned by ArrayList iterator() and listIterator() methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.ArrayList; import java.util.Iterator; import java.util.List; class Main { // Generic method to remove a specified element from the list public static <T> void filterList(List<T> list, T target) { Iterator<T> itr = list.iterator(); while (itr.hasNext()) { T t = itr.next(); if (target.equals(t)) { list.remove(t); // using `remove()` method of `List` interface } } } // Program to demonstrate fail-fast iterator in Java public static void main(String[] args) { List<String> colors = new ArrayList<>(); colors.add("BLUE"); colors.add("RED"); colors.add("RED"); colors.add("YELLOW"); // remove all instances of "RED" color from the specified list filterList(colors, "RED"); // print the filtered list System.out.println(colors); } } |
Output:
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at FailFast.filterList(Main.java:14)
at FailFast.main(Main.java:32)
2. Using For loop
|
1 2 3 4 5 6 7 8 9 10 |
// throws `ConcurrentModificationException` public static <T> void filterList(List<T> list, T target) { for (T t: list) { if (target.equals(t)) { list.remove(t); } } } |
3. Using Java 8 Stream
|
1 2 3 4 5 6 7 |
// throws `ConcurrentModificationException` public static <T> void filterList(List<T> list, T target) { list.stream() .filter(target::equals) .forEach(list::remove); } |
Fail Safe Iterator in Java
Iterator implementations that don’t throw ConcurrentModificationException when a thread modifies the structure of a collection while another thread or same thread is iterating over it are known as fail-safe iterators as they work on a new copy of the original collection.
CopyOnWriteArrayList is a thread-safe variant of the ArrayList in which all mutative operations (add, set, and so on) are implemented by making a new copy of the underlying array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; class Main { // Generic method to remove a specified element from the list public static <T> void filterList(List<T> list, T target) { Iterator<T> itr = list.iterator(); while (itr.hasNext()) { T t = itr.next(); if (target.equals(t)) { list.remove(t); // using `remove()` method of `List` interface } } } // Program to demonstrate fail-safe iterator in Java public static void main(String[] args) { List<String> colors = new CopyOnWriteArrayList<>(); colors.add("BLUE"); colors.add("RED"); colors.add("RED"); colors.add("YELLOW"); // remove all instances of "RED" color from the specified list filterList(colors, "RED"); // print the filtered list System.out.println(colors); } } |
Output:
[BLUE, YELLOW]
That’s all about the fail-fast iterator and fail-safe iterator in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)