Aakash Verma
Aakash Verma

Reputation: 3994

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?

Upvotes: 0

Views: 1371

Answers (2)

river
river

Reputation: 814

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.

Upvotes: 2

sauumum
sauumum

Reputation: 1788

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.

Upvotes: 0

Related Questions