Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fail-fast iterator creation question

Status
Not open for further replies.

DoraC

Programmer
Joined
May 7, 2002
Messages
98
Location
US
Hi,

I am required to create a new Collection (i.e. implements Collection interface) class, and as such I need to provide an iterator() method. This is no problem, I merely created an inner adaptor class to provide this functionality. However, most (maybe all) of the API Collection-class iterators are "fail-fast"... an iterator instance will throw a ConcurrentModificationException if any modification is made to the underlying collection outside of the iterator-instance's own remove() method. I've devised a means to accomplish this, but I was curious as to whether or not there is an "accepted way". My collection keeps track of all iterators open against it, and if a particular subset of iterators must "fail-fast", the collection sets flags within the instances to record this. The iterators, prior to performing any activity, check the value of this flag and throw exceptions accordingly.

This seems inefficient, totally prone to error, and perhaps not "the best way". Is there a "best way" and - if so - what is it?

Thank you!
dora


 
>> The iterators, prior to performing any activity, check
>> the value of this flag

I seem to remember reading that the Java API supplied fail-safe interators use a notification design. My understanding would be that the collection class notifies the iterators when the collection changes. I would interpret that wording to mean that in the design, the collection class would not have any state variable. But that is just a guess.

Was that what you were asking?
-pete

 
A peek into the source code for HashMap reveals that Sun keeps a private counter of the number of times the collection is modified. Prior to an iterator starting, it copies the value of this counter into a second variable, and then continually checks the private counter against it's local copy. When they're different, the exception is thrown.

I don't see where your method is any better or worse than this. If yours works, keep it and move on....

 
Thanks for the help.. appreciated as always.

I will keep the code as it is, and move on. There is currently no state variable in the collection class itself, just within the inner iterator class... it seems to work ;) so i'll content myself with it. I'm always concerned that there is a better, "industry-approved" means of accomplishing something that perhaps is more efficient or reveals something i'm totally unaware of.

Thanks again -
dora
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top