天天看點

java.util.ConcurrentModificationException異常[源于網絡]

ConcurrentModificationException主要原因及處理方法

當使用 fail-fast iterator 對 Collection 或 Map 進行疊代操作過程中嘗試直接修改 Collection / Map 的内容時,即使是在單線程下運作, java.util.ConcurrentModificationException 異常也将被抛出。

  Iterator 是工作在一個獨立的線程中,并且擁有一個 mutex 鎖。 Iterator 被建立之後會建立一個指向原來對象的單鍊索引表,當原來的對象數量發生變化時,這個索引表的内容不會同步改變,是以當索引指針往後移動的時候就找不到要疊代的對象,是以按照 fail-fast 原則 Iterator 會馬上抛出 java.util.ConcurrentModificationException 異常。

  是以 Iterator 在工作的時候是不允許被疊代的對象被改變的。但你可以使用 Iterator 本身的方法 remove() 來删除對象, Iterator.remove() 方法會在删除目前疊代對象的同時維護索引的一緻性。

  有意思的是如果你的 Collection / Map 對象實際隻有一個元素的時候, ConcurrentModificationException 異常并不會被抛出。這也就是為什麼在 javadoc 裡面指出: it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.

Iterator it = channelList.iterator();
			while (it.hasNext()) {
				ResChannel resChannel = (ResChannel) it.next();
				log.info("" + resChannel.getUniqueId() + "==== " + uniqueId);
				if (resChannel.getUniqueId().trim().equals(uniqueId.trim())) {
					it.remove();
					//channelList.remove(resChannel);
					return true;
				}

			}