Edit: Appearently the question has been marked a duplicate of this even though my question is about how to safely work with a list on one thread while another thread is modifying it, and the linked question is about how to remove during iterating.
Problem:
I have a List<Object> objects
in a class. This class also contains a getObjects()
method which returns the object list.
I have two threads working with this list. One thread is adding objects every now and then, and the other thread is doing stuff with them and removing it from the list once it's done. The problem occurs when I'm iterating over the list in thread two, while thread one adds an object to the list at the same time.
I have attempted to counter this, by having thread two only work with a copy of the list, and not the actual one. Using List<Object> newList = getObjects();
. Here I presumed that since newList is a different list(with the same objects though), that I could safely iterate over it and work with the objects. However it appears that this still causes the exception, because (I assume) the =
operator just makes newList a reference to the objects list. And that I'm still iterating over the objects list.
Question: So my question is: How do I safely work with the objects from the list in thread two?
Code: Even though I doubt it'll be of use for answering the question, here's the code(I removed all unneccesary clutter thats irrelevant to this question).
public class One
{
List<Object> objects;
public One()
{
objects = new ArrayList<Object>();
}
public void addObject(Object object)
{
objects.add(object);
}
public List<Object> getObjects()
{
return objects;
}
}
public class Two
{
private One one;
public Two(One one)
{
this.one = one;
}
public void processObjects()
{
List<Object> newList = one.getObjects();
for(Object object : newList) //Causes error because during iteration thread 1 adds an object to the objects list.
{
//dostuff with the object.
}
one.getObjects().removeAll(newList);
}
}