我有一个像下面这样的类:
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可以同时修改:一个是通过remove()一个线程,两个是通过getAllPersons().
我已经在多线程环境中测试了上述场景,看看是否可以通过在调用ConcurrentModificationException时返回浅拷贝来避免。getAllPersons()它似乎奏效了。我从来没有遇到过ConcurrentModificationException.
为什么,在这种情况下,只制作persons避免 a的浅表副本ConcurrentModificationException?