When debugging Java code using Eclipse, for collection variables, I saw the modcount
member. What does it mean?
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With