modCountはいったい何をしているのでしょうか


modCountはいったい何をしているのでしょうか
ArrayList、LinkedList、HashMapなどの内部で増、削除、変更を実現する中でmodCountの姿を見ることができます.modCountは文字通り修正回数を意味しますが、なぜmodCountの修正回数を記録するのでしょうか.modCountプロパティを使用するすべてのスレッドが安全ではないことに気づきました.これはなぜですか.これはスレッドの安全と関係があるに違いない.それは何の関係があるのだろうか.
ソースコードを読むと、このデータ構造対応反復器でしか使用されていないことがわかります.HashMapを例に挙げます.
private abstract class HashIterator<E> implements Iterator<E> {
        Entry next;        // next entry to return
        int expectedModCount;   // For fast-fail
        int index;              // current slot
        Entry current;     // current entry

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Object k = current.key;
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
    }

以上のコードから分かるように、1つの反復器が初期の時にこの反復器を呼び出すオブジェクトのmCountを与えることができて、どのように反復器が遍歴する過程の中で、いったんこのオブジェクトのmcountと反復器の中で記憶するmcountが異なることを発見したら、それは異常に良いことを投げて、下の面はこれの完全な解釈Fail-Fastメカニズムはjavaを知っています.util.HashMapはスレッドが安全ではないので、反復器を使用している間に他のスレッドがmapを変更した場合、ConcurrentModificationExceptionが放出されます.これがfail-fastポリシーです.このポリシーのソースコードでの実装はmodCountドメインによって行われ、modCountはその名の通り修正回数であり、HashMapコンテンツの修正にこの値が増加すると、反復器の初期化中にこの値が反復器のexpectedModCountに与えられる.反復中、modCountとexpectedModCountが等しいかどうかを判断し、等しくない場合は他のスレッドがMapを修正したことを示します.modCountがvolatileとして宣言されていることに気づき、スレッド間の修正の可視性を保証します.
ここでは、スレッド以外の安全なデータ構造を巡る場合は、できるだけ反復器を使用することをお勧めします.