HashMap and visibility

前端 未结 3 945
终归单人心
终归单人心 2021-02-13 11:33

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

3条回答
  •  执笔经年
    2021-02-13 12:19

    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:

    1. the theory should predict MAX i=1 on java 7
    2. before main() is executed, HashMap was probably iterated by other code, so the mentioned classes were probably loaded already.
    3. reader thread seeing a stale 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.

提交回复
热议问题