• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Iterator - Expected a ConcurrentModificationException but it does not throw this exception

 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
JDK: Sun 1.5.0_16
Also tried on jrockit81sp5_142_08

Just for curiosity, I was trying out the following code snippet:



I expect java.util.ConcurrentModificationException to be thrown and this code works as expected.

But when I try the same code with the second-last element ("Four" in this case), I do not get this exception. I get java.util.ConcurrentModificationException for "Five". I was expecting the behaviour to be consistent and since the list had been structurally modified, as per the specs, I should have got java.util.ConcurrentModificationException when I remove "Four" as well.

Am I missing anything?

 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The main thing you missed is this note in the API:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.


In short, CME is never guaranteed to be thrown. It may be thrown. I would say, there's a very good chance it will be thrown, if you're doing concurrent modifications, but don't count on it.

If you analyze the behavior carefully, you will find that this particular behavior occurs when you remove the next-to-last element of the list you're iterating through. By doing this, you "fool" the Iterator into thinking that the list has no more elements (since you're on the fourth element, and the size of the list is four - you must be done. So you finish the loop without another call to next(), and next() is the method that would have thrown the exception.
reply
    Bookmark Topic Watch Topic
  • New Topic