Search code examples
javafor-loopconcurrentmodification

java.util.ConcurrentModificationException in For loop


I am trying to program an IM software, I want to let user leave the conversation and tell his partner that he has left... I prefer to use for loop instead Iterator, seek all the users and get the user who ask to leave and remove him... like that:

   for(Clientuser Cu: EIQserver.OnlineusersList)
          if(Cu.ID.equals(thsisUser.ID)) // find the user who ask to leave 
          {
          Omsg.setBody("@@!&$$$$@@@####$$$$"); //code means : clien! ur parter leaves...
                 sendMessage(Omsg); // sed message to thje partner with that code
                 EIQserver.OnlineusersList.remove(Cu);// remove the partner
                EIQserver.COUNTER--;// decrease counter.

          }

I get Exception: java.util.ConcurrentModificationException

I was using iterators, and to get rid of this exception, I convert to for, but the same exception still appears!! how may I get rid of this exception?


Solution

  • Use Iterator instead of looping. For example:

    Iterator<Clientuser> iterator = EIQserver.OnlineusersList.iterator();
    while (iterator.hasNext()) {
        Clientuser next = iterator.next();
        if(next.ID.equals(thsisUser.ID)) {
            Omsg.setBody("@@!&$$$$@@@####$$$$"); 
            sendMessage(Omsg); 
            iterator.remove();// remove the partner
        }
    }