Fail-fast vs Fail-Safe Iterator in Java

Source: Internet
Author: User
Tags oracle docs concurrentmodificationexception

Reference

[1] http://netjs.blogspot.co.uk/2015/05/fail-fast-vs-fail-safe-iterator-in-java.html

The collections which is there from Java 1.2 (or even legacy) like ArrayList, vectors, HashSet, HashMap all has fail- Fast iterator whereas Concurrent collections added in Java 1.5 like Concurrrenthashmap, Copyonwritearraylist, copyonw Ritearrayset has Fail-Safe iterator.

The key differences between the fail-fast and fail-safe iterator

    1. fail-fast iterator throws concurrentmodificationexception if the underlying collection is Structurally modified in any except through the iterator ' s own remove or add methods.
      Fail-Safe iterator doesn ' t throw concurrentmodificationexception.
    2. Fail-fast iterator work on the original collection.
      Fail-Safe iterator makes a copy of the underlying structure and iteration is do over that snapshot. Drawback of using a copy of the collection rather than original collection are that the iterator would not reflect additions , removals, or changes to the collection since the iterator was created.
    3. fail-fast Iterator provides remove, set, and add operations. Note that is not all the iterators support all these methods. As exp. Listiterator supports Add () method But the general iterator doesn ' t.
      With Fail-Safe iterator element-changing operations on iterators themselves (remove, set, and add) is not suppor Re ". These methods throw unsupportedoperationexception.
Fail-fast iterator in Java

An iterator is considered fail-fast if it throws a concurrentmodificationexception under either of the F Ollowing conditions:

    • In multi-threaded environment, if one thread was trying to modify a Collection while another thread is iterating O Ver it.
    • Even with single thread, if a thread modifies a collection directly while it's iterating over the collection wit H a fail-fast iterator, the iterator would throw this exception.

Fail-fast iterator fails if the underlying collection is structurally modified at any time after the ITE Rator is created, thus the iterator would throw a concurrentmodificationexception if the underlying collection is Structurally modified in any- except through the iterator ' s own remove or add (if applicable as in List-iterat OR) methods.

Note that structural modification are 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 a existing key (in case of MAP) is not a structural modification.

Mostly iterators from Java.util package throw concurrentmodificationexception if collection is modified by collection ' s M Ethods (add/remove) while iterating

Also note that according to Oracle Docs fail-fast behavior of a iterator cannot be guaranteed as it is, generally spe Aking, impossible to do any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw concurrentmodificationexception on a best-effort basis. Therefore, it would is wrong to the write a program the depended on the this exception for its correctness:the fail-fast Behavio R of Iterators should is used only to detect bugs.

1) The following codes would throw Concurrentmodificationexception

 Public classfailfastmodification { Public Static voidMain (string[] args) {//Creating MapMap <String,String> CityMap =NewHashmap<string,string>(); Citymap.put ("1", "New York City" ); Citymap.put ("2", "New Delhi"); Citymap.put ("3", "Newark"); Citymap.put ("4", "Newport"); //getting iteratorIterator <String> ITR =Citymap.keyset (). iterator ();  while(Itr.hasnext ()) {System.out.println (Citymap.get (Itr.next ())); //trying to add new value to a map while iterating it, would throw ConcurrentmodificationexceptionCitymap.put ("5", "New City"); }            }}

2) The following method to just update values are allowed and would not throw concurrentmodificationexception

 Public classfailfastmodification { Public Static voidMain (string[] args) {//Creating MapMap <String,String> CityMap =NewHashmap<string,string>(); Citymap.put ("1", "New York City" ); Citymap.put ("2", "New Delhi"); Citymap.put ("3", "Newark"); Citymap.put ("4", "Newport"); //getting iteratorIterator <String> ITR =Citymap.keyset (). iterator ();  while(Itr.hasnext ()) {System.out.println (Citymap.get (Itr.next ())); //updating existing value while iteratingCitymap.put ("3", "New City"); }            }}

2) The following method to remove values using iterator itself is allowed and would not throw Concurrentmodificationexcepti On

 Public classfailfastmodification { Public Static voidMain (string[] args) {Map<String,String> CityMap =NewHashmap<string,string>(); Citymap.put ("1", "New York City" ); Citymap.put ("2", "New Delhi"); Citymap.put ("3", "Newark"); Citymap.put ("4", "Newport"); System.out.println ("Size before iteration" +citymap.size ()); Iterator<String> ITR =Citymap.keyset (). iterator ();  while(Itr.hasnext ()) {System.out.println (Citymap.get (Itr.next ())); //removing value using iterator Remove methodItr.remove (); } System.out.println ("Size after Iteration" +citymap.size ()); }}
Fail Safe iterator

in case of fail-safe iterator, concurrentmodificationexception are not thrown as the Fail-Safe iterator makes a co Py of the underlying structure and iteration are done on that snapshot.
Since iteration is do over a copy of the collection so interference are impossible and the iterator is guarantee D not to throw concurrentmodificationexception.

Drawback of using a copy of the collection rather than original collection are that the iterator would not reflect additions , removals, or changes to the collection since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) is not supported. These methods throw unsupportedoperationexception.

Iterator of Copyonwritearraylist is a example of fail-safe Iterator also Iterator provided by Concurrenthashmap KeySet are Fail-Safe and never throws concurrentmodificationexception.

Look at the following example of a fail-safe iterator

 Public classFailsafetest { Public Static voidMain (string[] args) {List<String> citylist =NewCopyonwritearraylist<string>(); Citylist.add ("New York City"); Citylist.add ("New Delhi"); Citylist.add ("Newark"); Citylist.add ("Newport"); Iterator<String> ITR =Citylist.iterator ();  while(Itr.hasnext ()) {System.out.println (Itr.next ()); Citylist.add ("Newcity"); //Itr.remove ();         } }}

This program won ' t throw concurrentmodificationexception as iterator used with copyonwritearraylist are fail-safe Iterator.

If we uncomment the line //itr.remove (); This program would throw unsupportedoperationexception as Fail-Safe iterator does not support remove, set, and add Oper Ations.

Summary
    • An iterator was considered fail-fast if it throws a concurrentmodificationexception in case the underlying collection ' s STR Ucture is modified.
    • While iterating a list or a map values can being updated, only if an attempt are made to add or remove from the collection Con Currentmodificationexception is thrown by Fail-fast iterator.
    • Fail-fast iterators throw concurrentmodificationexception on a best-effort basis and fail-fast behavior of a iterator can Not being guaranteed.
    • Fail-Safe iterator works with a copy of the collection rather than the original collection thus interference are impossible And the iterator is guaranteed not to throw concurrentmodificationexception.
    • Remove, set, and add operations is supported with fail-safe iterator.

Fail-fast vs Fail-Safe Iterator in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.