ConcurrentModificationException

843790
    i m using following code that throws ConcurrentModificationException
    Exception.......


    Set key = oldItem.keySet();
         Set dkey = oldItem.keySet();
    for( Iterator item=key.iterator(); item.hasNext(); ) {

    String keyItem=(String)item.next();

    if(keyItem.equals(""+iitemid)){

    if(dkey.size() > 0 ){
    dkey.remove(""+iitemid);
    }
    }else{
         ;
    }

    }

    it throws following exception :::


    java.util.ConcurrentModificationException
    java.util.ConcurrentModificationException at java.util.Hashtable$Enumerator.next(Unknown Source)

    pls help----
      • 1. Re: ConcurrentModificationException
        843790
        Once you modify a collection e.g. remove, any existing Iterator becomes invalid.
        You don't need to take the key set more than once.
        Are you trying to do
            oldItem.remove("" + iitemid);
        • 2. Re: ConcurrentModificationException
          843790
          This exception is usually thrown by either modifying something in one thread from another thread where you've not used synchronized or volatile (for methods or instance variables respectively) or (more likely from looking at your code) you're trying to modify the contents of your Collection as you're iterating through it.
          You probably need to use the iterators remove method rather than dkey.remove().
          • 3. Re: ConcurrentModificationException
            843790
            Just some tips for your code :

            don't use :
            if(keyItem.equals(""+iitemid)) but if(keyItem.equals(String.valueOf(iitemid)))

            if(dkey.size() > 0 ) but dkey.isEmpty. Imagine you have a set of million big elements.
            • 4. Re: ConcurrentModificationException
              843790
              do the below operation ... Although I am not sure of what exactly you are doing but having ref to keyset should be suffice. I am synchronized the collection assuming multiple threads have access to collection ... hope it helps

              synchronized(oldItem) {
              Set key = oldItem.keySet();
              long sizeOfOriginalSet = oldItem.keySet();
              for( Iterator item=key.iterator(); item.hasNext(); ) {
              String keyItem=(String)item.next();

              if(keyItem.equals(""+iitemid)){
              if(sizeOfOriginalSet > 0 ){
              item.remove(""+iitemid);
              }
              }else{
              ;
              }

              }

              • 5. Re: ConcurrentModificationException
                843790
                item.remove() will help. Check out Iterator for remove() method, when and how it can be used.