java - Adding and removing elements to a Collection -
i'm new java , i'm making game player has eat cookies. these cookies elements of arraylist. arraylist modified 2 threads : -one iterates on , removes cookies have been eaten, using iterator.remove() -one adds cookie arraylist every 5 seconds
sometimes concurrentmodificationexception, , know it's because behavior of iterator.remove() "unspecified if underlying collection modified in other way while iteration in progress", stated in java tutorial sun. how should proceed ?
edit : updated code with
list<cupcake> cake = collections.synchronizedlist(new arraylist<cupcake>());
here's 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(); } } }
arraylist not threadsafe implementation of list.
use copyonwritearraylist instead - not cause explosion if add elements while iterating.
Comments
Post a Comment