简体   繁体   English

通过列表迭代,同步并使用迭代器时发生ConcurrentModificationException

[英]ConcurrentModificationException on iteration through list, synchronized and using iterators

How is it possible to get a ConcurrentModificationException for this code-block? 如何获得此代码块的ConcurrentModificationException?

synchronized (list) {
        for (Iterator<?> it = list.iterator(); it.hasNext(); ) {
            Object object = it.next();
            // do something to object without touching list
        }
}

Edit: sorry, that was not specific enough: // do something to object does not touch the list 编辑:对不起,这还不够具体://对对象执行某些操作不会触摸列表

By having another thread modifying the list, for example. 例如,通过另一个线程修改列表。

Just because you synchronize this code block doesn't mean all the accesses to the list are blocked. 仅仅因为同步该代码块并不意味着所有对列表的访问都被阻止。 It only makes sure that all the other blocks synchronized on the list can't execute in parallel. 它仅确保列表上同步的所有其他块不能并行执行。

If the list is shared by several threads, all its usages must be synchronized on the same monitor. 如果该列表由多个线程共享,则必须在同一监视器上同步其所有用法。

If the "do something" directly or indirectly adds or removes something from list (except by using it.remove() or similar), then you'll get this exception. 如果“执行某项操作”直接或间接地从list添加或删除了某项(使用it.remove()或类似方法除外),则将得到此异常。 The synchronization won't stop it from happening in this case. 在这种情况下,同步不会阻止它的发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM