简体   繁体   中英

Multiple threads using iterator.remove() on a single collection returning fail-fast iterator

Oracle says

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Could this mean that even if multiple threads are iterating together over the same collection's fail-fast implementation's ( Vector , Hashmap , ArrayList , HashSet ) object carry out iterator.remove() there would be no ConcurrentModificationException thrown?

No. This tells you that only safe way to remove elements while iterating (in one thread) is to use iterator.remove. And if collection is accessed (iterated or modified) from other threads - sometime you will get exception, sometime not - in general behavior is not deterministic so you should avoid using it or relying on it.

That being said - only exception to this are Concurrent collections.

It does not mean multiple thread can remove data using iterator.remove().

If you want to achieve it you need to use Synchronized type of collections. Even in that case you should not try to use the same iterator in two threads. If you have two threads that need to remove entry, then they each should have their own iterators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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