1

Possible Duplicate:
java.util.ConcurrentModificationException on ArrayList

I am trying to remove items from a list inside a thread. I am getting the ConcurrentModificationException. I read from this link that it's related to removing items from list. I am putting the sample code below. How can I do this properly without this exception in my case.

try 
{
    for(Game game:appDeleg.getGlobalGames().getGames())
    {
        if(game.getOwner().getId().equals(params[0]))
        {
            synchronized (appDeleg.getGlobalGames().getGames())
            {
                appDeleg.getGlobalGames().getGames().remove(game);
            }
        }

    }
}

catch (Exception e) 
{
    e.printStackTrace();
    return "noconnection";
}
Community
  • 1
  • 1
Zach
  • 9,989
  • 19
  • 70
  • 107

5 Answers5

5

use Iterator:

Iterator<Game> i = appDeleg.getGlobalGames().getGames().iterator();

Game game;
while(i.hasNext()) {
    game = i.next();
    if(game.getOwner().getId().equals(params[0]))
          i.remove();
    }
}
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

The enhanced for loop uses an iterator. The iterator can throw an exception if something modifies the collection as it is iterating through it.

In your case you are removing the item through the collection not through the iterator.

Try use a standard for loop and not using the implied iterator. Assuming your collection is an array list.

ArrayList games = appDeleg.getGlobalGames().getGames();
for(int i=0;i<games.size();i++){
      Game game = games.get(i);
      if(game.getOwner().getId().equals(params[0])){
       games.remove(i);

      }
}
barconr
  • 197
  • 1
  • 11
1

Collect the to be removed items in a new list and remove them after you looped through the original list.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
1

synchornized keyword will not protect you here.
You can reach this exception event from single-threaded appication (yes - you may claim the name of the exception is misleading).
This should be done using iterator to iterate over the list,
(Which will allow you to call remove when you reach the value you want to remove),
or by collecting the elements you want to remove to a separate list, and then run the removeAll method on it.

Yair Zaslavsky
  • 4,091
  • 4
  • 20
  • 27
1

You can not remove item of a list while iterating, it throws ConcurrentModificationException

If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

docs -> link

you should you Iterator for removing item from list.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103