标签:
为了保证线程安全,在迭代器迭代的过程中,线程是不能对集合本身进行操作(修改,删除,增加)的,否则会抛出ConcurrentModificationException的异常。
1 public static void main(String[] args) { 2 Collection num = new ArrayList<String>(); 3 num.add("One"); 4 num.add("Two"); 5 num.add("Three"); 6 7 Iterator<String> iterator= num.iterator(); 8 while(iterator.hasNext()){ 9 String element = iterator.next(); 10 if("One".equals(element)){ 11 iterator.remove(); 12 }else { 13 System.out.println(element); 14 } 15 } 16 } 17 }
Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at com.mobin.thread.IterationTest.main(IterationTest.java:20) //错误代码对应上面的11行
public boolean hasNext() { return cursor != size; }
1 public E next() { 2 checkForComodification(); 3 int i = cursor; 4 if (i >= size) 5 throw new NoSuchElementException(); 6 Object[] elementData = ArrayList.this.elementData; 7 if (i >= elementData.length) 8 throw new ConcurrentModificationException(); 9 cursor = i + 1; 10 return (E) elementData[lastRet = i]; 11 }
if("Two".equals(element)){ //条件发生了改变,对第二个元素进行判断 num.remove(element); }else { System.out.println(element); }
One
1 public boolean hasNext() { 2 return cursor != size; 3 }
Collection num = new CopyOnWriteArrayList();
1 public boolean add(E e) { 2 final ReentrantLock lock = this.lock; //重入锁 3 lock.lock(); //加锁,效果与synchronized一样 4 try { 5 Object[] elements = getArray(); 6 int len = elements.length; //得到数组长度 7 Object[] newElements = Arrays.copyOf(elements, len + 1); //复制元素到一个新数组里 8 newElements[len] = e; //原数组指向新数组 9 setArray(newElements); 10 return true; 11 } finally { 12 lock.unlock(); //在finally里解锁是为了避免发生死锁 13 } 14 }
if("Two".equals(element)){ iterator.remove(); //修改了此行 }else { System.out.println(element); }
集合的操作出现的ConcurrentModificationException(源码分析)
标签:
原文地址:http://www.cnblogs.com/MOBIN/p/5340735.html