避免对名单ConcurrentModificationException的我有类似下面的类:通过使浅拷贝
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
可以同时修改:通过由getAllPersons()
返回的浅复制的实例是通过remove()
由一个线程和两个。
我已经在多线程环境中测试了上述场景,以便在调用getAllPersons()
时通过返回浅拷贝来避免ConcurrentModificationException
。它似乎工作。我从未遇到过ConcurrentModificationException
。
为什么在这种情况下,只做persons
的浅拷贝避免ConcurrentModificationException
?
http://stackoverflow.com/questions/19384056/how-to-concurrently-modify-a-vector/19384832?noredirect=1#comment28729008_19384832 –