Compare hotel prices and find the best deal - HotelsCombined.com

Tuesday, January 6, 2015

What is ConcurrentModificationException in collection? in which situation it will come?give me example.

What is ConcurrentModificationException in collection? in which
                         situation it will come?give me example.   
             
 Answer :-  The java.util Collection classes are fail-fast, which means that if one
                  thread changes a collection while another thread is traversing it
                 through with an iterator the iterator.hasNext() or iterator.next()
                 call will throw  ConcurrentModificationException.  This situation can
                come in case of  multithreaded as well as single threaded
                 environment. 
        
           Lets see the scenario with an example:
                             import java.util.*;
                             public class IteratorEx{
                                public static void main(String[] args){
                                         List list=new ArrayList();
                                                   list.add("one");
                                                   list.add("two");
                                                   list.add("three");
                                        Iterator  it=list.iterator();
                                         while(it.hasNext()){
                                                      String key=it.next();
                                                       if(key.equals("two")){
                                                              list.remove("two");    //will throw error
                                                            }
                                                    }
                                         }
                              }

                 How to handle the 
ConcurrentModificationException:--

      1) The list can be converted to an array with list.toArray() and iterate on the
          array.  This approach is not recommended if the list is large. 
      2)  You can lock the list while iterating by putting it in a synchronized block. 
          This approach is not recommended because it will cease the benefits of 
          multithreading .
      3) If you are using JDK1.5 or higher then you can use ConcurrentHashMap
          and CopyOnWriteArrayList classes. It is the recommended approach. 
      4)  if you are removing element from collection then use iterator remove
          method instead of  collection remove method .