I am writing a multi-threaded platform game. One thread does the painting job, the other thread, runs the game logic. I have an array-list that both threads need to access at the same time. I am iterating over all the elements of the array-list in my paint thread, and in my other thread, i sometimes remove or add elements to the array-list. I get a concurrent-modification-exception but i don't understand why because doesn't the volatile keyword only allow one thread to access a variable at a time.
Here is an example of my problem
my arraylist
private volatile ArrayList<Entity> entities = new ArrayList<Entity>();
my painting code
for(Entity entity : entities)
{
if(entity!=null && entity.getX()>=xs-Block.WIDTH && entity.getX()<=xs+Main.WIDTH)
g.drawImage(entity.getImage(), entity.getX()-getXs(), entity.getY(), entity.getWidth(), entity.getHeight(), null);
}
my remove code
public void removeEntity(Entity e)
{
entities.remove(e);
}