As we all know, iterating without synchronization on a collection risks throwing ConcurrentModificationException
if another thread happens to concurrently modify the collection.
But what about calling size()
on the collection? Does size()
involve iteration to count the number of elements in the collection? If that is the case, ConcurrentModificationException
may occur (some people report this, for example here, but for me it is not clear that size() was the culprit).
On the other hand, if size()
just gets an internal int
counter variable, no exception would occur.
Which one is the case?
HUMBLE EDIT: Thanks to the answerers for the precision that this depends on the implementation. I should have mentioned that it is a TreeMap. Can I have this problem with that map? The docs say nothing about TreeMap.size().