Khi tôi thực hiện đoạn mã sau, tôi nhận được ConcurrentModificationExceptionJava: ConcurrentModificationException khi iterating trên danh sách
Collection<String> myCollection = Collections.synchronizedList(new ArrayList<String>(10));
myCollection.add("123");
myCollection.add("456");
myCollection.add("789");
for (Iterator it = myCollection.iterator(); it.hasNext();) {
String myObject = (String)it.next();
System.out.println(myObject);
myCollection.remove(myObject);
//it.remove();
}
Tại sao tôi lại nhận được ngoại lệ, mặc dù tôi đang sử dụng Collections.synchronizedList?
Khi tôi thay đổi myCollection để
ConcurrentLinkedQueue<String> myCollection = new ConcurrentLinkedQueue<String>();
Tôi không nhận được ngoại lệ đó.
ConcurrentLinkedQueue trong java.util.concurrent khác với Collections.synchronizedList như thế nào?
Bản sao có thể có của [Iterating through a Collection, tránh ConcurrentModificationException khi loại bỏ trong vòng lặp] (http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Raedwald