1

I know there is a InnerClass named"Itr" in java.util.AbstractList. and there is a field named "expectedModCount", a method named "checkForComodification". when iterator a collection but update the collection, this method will throw the ConcurrentModificationException I want to know why java language designed like this? what is the purpose to do like this.

Thx !

Tangc
  • 11
  • 1
  • It is worth nothing that the concurrent collections do not do this. Additionally this field is not `volatile` and there is no guarantee that a ConcurrentModificationException will be thrown. – Peter Lawrey Jul 23 '12 at 09:35

4 Answers4

8

I want to know why java language designed like this?

It's not part of the language. It's part of the collection framework.

Basically, it's relatively hard to make a very general specification about what should happen if you're iterating over a collection and it changes underneath you. While you could certainly decide on some rules for a list, what about (say) the entry set for a map? Adding or removing entries could change the internal order entirely - what would you want to happen then?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

If it was allowed to change the collection you get a lot of problematic casses.

Say we have a list with elements 0 to 4 the iterator is just passed 3

 
|0|1|2|3|4|
iterator^

now we add an element at the begining

 
|5|0|1|2|3|4|
iterator^?^

What should the iterator return now?

  • it could return 4 since that was the next element before the change
  • it could return 3 since that is now at the index where the iterator was pointing at

Depending on the list implementation each of these also adds complexity and has a performance penalty, by forbidding the modification of collections we can avoid the specifying a correct behavior and the attached complexity.

josefx
  • 15,506
  • 6
  • 38
  • 63
1

You can iterate over a collection and modify it using Iterator (which is the standard way to do this).

See Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop for more discussion around this.

Community
  • 1
  • 1
1

If a collection is modified by one thread while another reads from it, there might happen what we call a Race Condition . Avoiding it costs some performance, but you avoid unpredictable/unwanted results (e.g. you might skip or read twice an existing element in an ArrayList if there was no such check).

Javier
  • 678
  • 5
  • 17
  • @josefx It is probable that the asker's case is single threaded, but he asked why (and Collections designers should have concurrency in mind). I don't understand what's your point. – Javier Jul 23 '12 at 10:22
  • sorry, most problems mentioning ConcurrentModificationException are single threaded problems and since the collection framework almost completely ignores threads I assumed that ConcurrentModificationException was centered on single threaded problems. – josefx Jul 23 '12 at 13:18