Why iterator is fail safe
ListIterator supports add method but the general iterator doesn't. With fail-safe iterator element-changing operations on iterators themselves remove, set, and add are not supported. These methods throw UnsupportedOperationException. Now let us see some detailed explanation and supporting programs to see these features of both fail-fast and fail-safe iterators.
An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:. The iterator will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add if applicable as in ListIterator methods.
Note that structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element in case of list or changing the value associated with an existing key in case of map is not a structural modification. Mostly iterators from java. Also note that according to Oracle Docs fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.
Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. For example, the following methods will throw a ConcurrentModificationException as they permit concurrent modification on an ArrayList instance:. ArrayList ; import java. Iterator ; import java.
Download Run Code. ConcurrentModificationException at java. 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. List ; import java. Reinforcement Learning. R Programming. React Native. Python Design Patterns. Python Pillow. Python Turtle. Verbal Ability. Interview Questions. Company Questions. Artificial Intelligence.
Cloud Computing. Data Science. Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design. Computer Organization. Discrete Mathematics. Ethical Hacking. Computer Graphics. Software Engineering. Web Technology. For example, in case of ConcurrentHashMap, it does not operate on a separate copy although it is not fail-fast. Instead, it has semantics that is described by the official specification as weakly consistent memory consistency properties in Java.
ConcurrentHashMap; import java. This means that this iterator can tolerate concurrent modification, traverses elements as they existed when iterator was constructed and may but not guaranteed to reflect modifications to the collection after the construction of the iterator. Skip to content. Change Language. Related Articles. Table of Contents. Save Article. Improve Article. Like Article. Next ConcurrentHashMap in Java.
0コメント