`
wangtong40
  • 浏览: 249042 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ConcurrentModificationException

阅读更多

ConcurrentModificationException
一个不该犯的低级错误,今天的代码突然抛了一个concurrentModificationException错误,
Iterator的一个基本概念没有掌握导致的这个错误,就是在Iterator的实现类
比如Hashtable里面的内部类
 private class Enumerator<T> implements Enumeration<T>, Iterator<T>

会在next,或者remove的时候检查当前集合是否会在修改状态,如果是的话
就会抛出 ConcurrentModificationException,而他自己remove则是使用了同步的方法
而且同步了modCount;expectedModCount;

 

public T next() {
     if (modCount != expectedModCount)
  throw new ConcurrentModificationException();
     return nextElement();
 }


public void remove() {
     if (!iterator)
  throw new UnsupportedOperationException();
     if (lastReturned == null)
  throw new IllegalStateException("Hashtable Enumerator");
     if (modCount != expectedModCount)
  throw new ConcurrentModificationException();

     synchronized(Hashtable.this) {
  Entry[] tab = Hashtable.this.table;
  int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;

  for (Entry<K,V> e = tab[index], prev = null; e != null;
       prev = e, e = e.next) {
      if (e == lastReturned) {
   modCount++;
   expectedModCount++;
   if (prev == null)
       tab[index] = e.next;
   else
       prev.next = e.next;
   count--;
   lastReturned = null;
   return;
      }
  }
  throw new ConcurrentModificationException();
     }
 }
    }
 

而自己在next的同时,修改了这个集合,导致了这个错误的出现

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics