Iterative collection in two threads

This question applies to both C # and Java

If you have a collection that is not modified and that the collection reference is shared between two threads, what happens when you iterate over each thread?

ThreadA: Collection.iterator ThreadA: Collection.moveNext ThreadB: Collection.iterator ThreadB: Collection.moveNext

Will threadB see the first element?

Does an iterator always reset when it is requested? What happens if this alternates, so the movenext and the element alternate? Is there a danger that you are not processing all the elements?

+4
source share
5 answers

It works as expected, because every time you request an iterator, you get a new one.

If you hadn’t done this, you couldn’t have done foreach, and then foreach in the same collection!

+3
source

By convention, the Iterator is implemented so that the bypass action never changes the state of the collection. It only indicates the current position in the collection and controls the iteration logic. Therefore, if you scan the same collection on N different threads, everything should work fine.

However, note that Java Iterator allows you to delete items, and ListIterator even supports an established operation. If you want to use these actions with at least one of the threads, you will probably encounter concurrency problems (ConcurrentModificationException) if the Iterator is not specifically designed for such scenarios (for example, with ConcurrentHashMap iterators).

+2
source

In Java (and I'm also sure in C #), standard API collections usually don't have a single iterator. Each call to iterator() creates a new one that has its own internal pointer or pointer, so that while both threads receive their own iterator object, there should be no problem.

However, this is not guaranteed by the interface, as well as the ability of two iterators to work simultaneously without problems. For custom collection implementations, all bets are disabled.

+1
source

At least in C #, all standard collections can be listed simultaneously on different threads. However, enumeration to any stream will explode if you change the base collection during enumeration (as it should be.) I do not believe that any sensible developer creating a collection class will have its own counters mutating the state of the collection in such a way that interferes with the listing, but it is possible. However, if you use a standard collection, you can safely assume this and, therefore, use locking strategies, such as Single Writer / Multiple Reader, when synchronizing access to the collection.

0
source

Source: https://habr.com/ru/post/1306598/


All Articles