Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threadsafe iteration over non-indexed collection?

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

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,
Yuriy
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic