This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Does a way exist for multiple threads to iterate over the same collection without interfering with one another and without using indexes or toArray()? As I understand it, each collection object only has one instance of an iterator, so two threads can't use it to independently iterate through the collection.
I don't think that is correct. You can create as many iterators as you like on a collection. However, if you modify the collection through any means while iterating, typical collections will throw a concurrent modification exception. You can modify the collection through one iterator, but the other iterators will probably throw an exception when you try to get the next item.
If you have just one iterator, then you can modify the collection, through the iterator, without any concurrent modification exceptions being thrown.
I don't know that this is a thread related issue really, but it is a concurrency issue.
C.L. is correct. The whole point of having Iterator objects is so that they can hold the iteration state -- otherwise, you could just put startIterating(), next(), and hasNext() methods onto the collection itself, right?
He's also right in that modifying a collection through one Iterator may break other open iterators. The only defense against that is to iterate over a private copy of a container, not the container itself.
Ah, I see, so as long as each thread iterates completely within a synchronized block, from the creation of the iterator to the last time that specific iterator is used, and assuming other modification methods are called from within blocks synchronized on the same object, there should be no problems?
Thank you, Yuriy
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Threadsafe iteration over non-indexed collection?