I'm new to Java and I'm currently making this game where the player has to eat some cookies. These cookies are elements of an ArrayList. This ArrayList is modified by two threads : -one that iterates over it and removes the cookies that have been eaten, using Iterator.remove() -one that adds a cookie to the ArrayList every 5 seconds
Sometimes I get a ConcurrentModificationException, and I know it's because the behavior of Iterator.remove() is "unspecified if the underlying collection is modified in any other way while the iteration is in progress", as stated in the Java Tutorial from Sun. How should I proceed ?
EDIT : updated code with
List<Cupcake> cake = Collections.synchronizedList(new ArrayList<Cupcake>());
Here's the Spawner :
public class CupcakeSpawner extends Thread {
private Background back;
public CupcakeSpawner(Background back) {
this.back = back;
}
public void run() {
while(true) {
if(back.getCake().size() < 15)
back.getCake().add(new Cupcake());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
My update method :
public void update() {
List<Cupcake> cake = back.getCake();
Iterator<Cupcake> itrC = cake.iterator();
while(itrC.hasNext()) {
Cupcake cupcake = (Cupcake)(itrC.next());
checkCollisionCup(cupcake);
if(cupcake.isEaten())
itrC.remove();
}
}
}