fail-fast机制

226 阅读1分钟

之前在看jdk集合包的源码的时候,经常会看到modCount这个变量。 这个modCount主要用于fail-fast,像ArrayList,LinkedList,HashMap都是非线程安全的

private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;
}

public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }

final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

在遍历的时候都会检查一下集合有没有被修改过,如果被修改过就抛出异常ConcurrentModificationException停止遍历