Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the modcount variable when debugging the collection [duplicate]

When debugging Java code using Eclipse, for collection variables, I saw the modcount member. What does it mean?

like image 812
Adam Lee Avatar asked Jun 14 '12 23:06

Adam Lee


People also ask

What is modCount in Java?

protected transient int modCount = 0; is the property declared at public abstract class AbstractList , to identify total number of structural modification made in this collection. Means if there is a add/remove there will be an increment in this counter for both operation.

What is modCount in Hashmap?

It's a counter used to detect modifications to the collection when iterating the collection: iterators are fail fast, and throw an exception if the collection has been modified during the iteration. modCount is used to track the modifications.

Does Iterator throw a ConcurrentModificationException?

If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException.


1 Answers

Many of Java's collections produce iterators that are "fail-fast", which means that if the collection is changed after an iterator is created, the iterator will be invalidated and throw a ConcurrentModificationException as soon as it can. (As compared to failing later or returning invalid data.)

In order to support this functionality, the collection has to keep track of whether it has been modified. Each time the collection is changed, it increments modcount. When the collection produces an iterator, the iterator stores the value of modcount from when it was created. Then whenever you try to use the iterator, it checks to see if its saved modcount is different from the parent collection's current modcount; if it is, the iterator fails with a ConcurrentModificationException.

(An exception to this rule is that modifications to the collection made through the iterator itself (like the iterator's remove method) do not invalidate the iterator.)

like image 83
matts Avatar answered Sep 21 '22 15:09

matts