Search code examples
javamultithreadingsynchronizedvolatileconcurrentmodification

Volatile arraylist not acting as expected


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);
}

Solution

  • 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.