I have a class like the following:
class Test
{
private LinkedList<Person> persons = new LinkedList<Person>;
public synchronized void remove(Person person)
{
persons.remove(person);
}
public List<Person> getAllPersons()
{
// Clients may iterate over the copy returned and modify the structure.
return new ArrayList<Person>(persons);
}
}
persons
may be modified concurrently: one is via remove()
by one thread and two via the shallow copied instance returned by getAllPersons()
.
I have tested the above scenario in a multithreaded environment to see if I can avoid ConcurrentModificationException
by returning a shallow copy when getAllPersons()
is called. It seemed to work. I have never once encountered a ConcurrentModificationException
.
Why, in this case, does making only a shallow copy of persons
avoid a ConcurrentModificationException
?