1
votes

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);
}
3
please post code if you have tried someAbubakkar

3 Answers

3
votes

No, it doesn't. volatile keyword only guarantees you that any modifications to variable which is declared volatile will be seen to all of the threads.

You need to synchronize your code correctly or use CopyOnWriteArrayList, for example.

0
votes

Instead of using volatile use Collections.synchronizedList(list);

0
votes

You can use vector , which is synchronized .

Vector

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized.