File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Threadsafe iteration over non-indexed collection? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threadsafe iteration over non-indexed collection?" Watch "Threadsafe iteration over non-indexed collection?" New topic

Threadsafe iteration over non-indexed collection?

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429

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.

Thank you,
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

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.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
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,
I agree. Here's the link:
subject: Threadsafe iteration over non-indexed collection?
jQuery in Action, 3rd edition