3 Replies Latest reply on Dec 15, 2003 8:11 PM by 843798

    ConcurrentModificationException is thrown when using an Iterator....

    843798
      Hi,

      I am getting a really weird error..I have an Iterator on a HashSet; the access to the HashSet objects is only via synchronized methods ..thus according to me..they should not be accessible to other threads while one thread has locked them..even in this situation it is throwing a ConcurrentModificationException when I am iterating on the iterator...please let me know if I have missed something here... Here is my code::
      import java.util.*;
       
      public class TestStore {
      
       private Set newData = Collections.synchronizedSet(new HashSet());
       private Set oldData = Collections.synchronizedSet(new HashSet());
       private boolean finished = false;
       
       public TestStore() {
       }
       
       /**
        * Threads add some data to the newData set if that data
        * has not been read by the user yet...
        */
       public synchronized void addData(String data) {
        if(!oldData.contains (data))
         newData.add(data);
       }
       
       /**
        * Threads reads the data..and gives the method of the
        * expected number of data it needs back...however it 
        * is possible that the user gets less than it asked
        * for.
        */
       public synchronized ArrayList getRelationship(int nosofData){
       ArrayList result = new ArrayList();
       
       //This was just a lame experiment...
       synchronized(TestStore.class) {
        try {
          Iterator itr = newRels.iterator ();
          int nos = 0;
       
          while( itr.hasNext () && (nos++ < nosofData)){
            //This is where it is failing...
            //It runs one time the next time in the while loop it
            // gives me a ConcurrentModificationException.
            String tmp = (String)itr.next ();
            result.add (tmp);
            newData.remove (tmp);
            oldData.add (tmp);
          }
         }catch(Exception ex){
           ex.printStackTrace ();
         }
         return result;
         }//end of the sync block
       }     
      }
      Any Help would be appreciated..

      Thanks,

      Sumit