File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Iterator - Expected a ConcurrentModificationException but it does not throw this exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Iterator - Expected a ConcurrentModificationException but it does not throw this exception" Watch "Iterator - Expected a ConcurrentModificationException but it does not throw this exception" New topic
Author

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

Sunil Vasudevan
Ranch Hand

Joined: Mar 05, 2007
Posts: 107
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?


Sunil.V<br />SCJP2, SCWCD1.4, SCBCD1.3
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Iterator - Expected a ConcurrentModificationException but it does not throw this exception