HashMap\'s javadoc states:
if the map is structurally modified at any time after the iterator is created, in any way except through the iterator\'s own re
My theory is that on both Java 6&7, creating the iterator in the reader thread takes longer time than putting 100 entries in the writer thread, mainly because new classes have to be loaded and initialized (namely EntrySet, AbstractSet, AbstractCollection, Set, EntryIterator, HashIterator, Iterator
)
So the writer thread has finished by the time this line is executed on the reader thread
HashIterator() {
expectedModCount = modCount;
if (size > 0) { // advance to first entry
In Java 6, since modCount
is volatile
, the iterator sees the latest modCount and size
, so the rest of iteration goes smoothly.
In Java 7, modCount
is not volatile, the iterator probably sees stale modCount=3, size=3
. After sleep(1)
, the iterator sees updated modCount
, and fails immediately.
Some flaws with this theory:
MAX i=1
on java 7HashMap
was probably iterated by other code, so the mentioned classes were probably loaded already.modCount
is possible, but not likely, since it's the first read of the variable on that thread; there's no prior cached value.We may get to the bottom of this problem by planting logging code in Hashmap to find out what the reader thread is seeing.