Posted on 2007-01-23 11:31
Dr.Water 閱讀(3483)
評(píng)論(1) 編輯 收藏 所屬分類:
Java 隨手貼
ConcurrentModificationException
一個(gè)不該犯的低級(jí)錯(cuò)誤,今天的代碼突然拋了一個(gè)concurrentModificationException錯(cuò)誤,
Iterator的一個(gè)基本概念沒有掌握導(dǎo)致的這個(gè)錯(cuò)誤,就是在Iterator的實(shí)現(xiàn)類
比如Hashtable里面的內(nèi)部類
?private class Enumerator<T> implements Enumeration<T>, Iterator<T>
會(huì)在next,或者remove的時(shí)候檢查當(dāng)前集合是否會(huì)在修改狀態(tài),如果是的話
就會(huì)拋出 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的同時(shí),修改了這個(gè)集合,導(dǎo)致了這個(gè)錯(cuò)誤的出現(xiàn)