I am still at an early stage of developing a game in Android (in Java) and I have run into a Concurrency issue with adding/removing Objects from my Game loop.
The application has 2 separate fragments, one which is a controller and the other is the SurfaceView displaying the Game loop. The controller has buttons which prompts the creation of Objects which are then added to the Game loop. The Concurrency issue pops up seemingly randomly, but mostly when an Object is removed from the ArrayList storing it and another is being added to it to be drawn.
The crashes do not happen uniformly or at the same points during running so I am at a loss here. I have already switched all my For-each loops over to ListIterator add/remove calls thinking it would stave off the Concurrency problems but it has proven to be ineffective.
Am I going to have to employ locking with my Object adds until after the next completion of draw() or is there another way?
Thanks in advance.
Edit:
// Adds new Objects to ArrayList
ListIterator<Projectile> iterator = curr_player.getProjectiles().listIterator();
iterator.add(new_p);
// Code to remove Object when it goes off View Boundaries
public boolean projectileBoundary()
{
Projectile p;
for (ListIterator<Projectile> iterator = curr_player.getProjectiles().listIterator(); iterator.hasNext();)
{
p = iterator.next();
if (p.getX() > p.getXMax())
{
iterator.remove();
return true;
}
}
return false;
}
// Objects drawn to canvas using this function
public void drawProjectiles()
{
for (Iterator<Projectile> iterator = curr_player.getProjectiles().iterator(); iterator.hasNext();)
{
Projectile p = iterator.next();
drawProjectile(p);
}
}
As was previously stated the application does NOT crash only when removing it happens before deletions ever occur. Which indicates there is a problem updating the ArrayList that is being drawn with the new Objects being added to it concurrently.
The application terminates in the error: java.util.ConcurrentModificationException at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)