Iterators and Deadlocks: How Not to Use Iterators!

Two nice little bugs today which sums up most of my day ;-)

How not to use iterators:


while(views.iterator().hasNext()) {
View currentView = (View) views.iterator.next();
currentView.update();
}

Bing that basically crashed my Firefox (this is part of a GWT app) when running it as well as my Netbeans / GWT debugger. Notice that Firefox was so good to tell me that apparently the script I was running in a weird manner.

And it was indeed in an endless loop as you can guess: invoking the iterator() method returns a new Iterator object every time (which it is supposed to do, I’m the dumb one in that story). Thus, I was basically getting the same “next()” object every time and hasNext() was thus always true ;-)

Anyway that fixes it:


Iterator viewsIt = views.iterator();
while(viewsIt.hasNext()) {
View currentView = (View) viewsIt.next();
currentView.update();
}

Ok that was a trivial one, but actually so trivial that I just felt like shaming me a little more and publishing it here :-)

Leave a comment

Your comment