posts - 9, comments - 8, trackbacks - 0, articles - 3
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

ConcurrentModificationException

Posted on 2007-01-23 11:31 Dr.Water 阅读(3466) 评论(1)  编辑  收藏 所属分类: Java 随手贴

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的同时,修改了这个集合,导致了这个错误的出现


评论

# re: ConcurrentModificationException  回复  更多评论   

2010-11-01 13:00 by 呆呆地
操 怎么修改你咋不说

只有注册用户登录后才能发表评论。


网站导航: