迭代器并发修改异常

jav*_*eek 2 java collections iterator exception synchronized

如果在doSomething()中修改了列表,则此代码将抛出Concurrent Modification Exception.是否可以通过将代码封装在某个同步块中来避免它?

List l = Collections.synchronizedList(new ArrayList());

// normal iteration -- can throw ConcurrentModificationException
// may require external synchronization
for (Iterator i=list.iterator(); i.hasNext(); ) {
  doSomething(i.next());
}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 7

  • 如果要从列表中删除项目,可以通过调用iterator.remove()而不是list.remove(iterator.next())

  • 如果你要添加一个项目 - 好吧,创建一个迭代列表的副本并将其添加到那里

  • 如果上面的代码片段是同一方法的一部分,那么您不需要同步列表或同步块 - 没有其他线程可以访问本地列表.