1. Fail-Fast (fail—fast)

When using an iterator to traverse a collection object, if the contents of the collection object are modified (added, deleted, or modified) during the traversal, a Concurrent Modification Exception will be thrown.

Principle:The iterator directly accesses the contents of the collection during traversal and uses a modCount variable during the traversal. If the contents of the collection change while it is being traversed, the value of modCount will be changed. Every time the iterator uses hashNext()/next() to traverse to the next element, it checks whether the modCount variable is equal to the expectedmodCount value. If so, it returns to the traversal; otherwise, it throws an exception and terminates the traversal.

Note:The condition for throwing an exception here is detectingmodCount != expectedmodCountthis condition. If the modCount value is set back to the expectedmodCount value just when the collection changes, the exception will not be thrown. Therefore, you cannot rely on whether this exception is thrown when programming concurrent operations; this exception is only recommended for detecting bugs in concurrent modifications.

Scenarios:The collection classes under the java.util package are all fail-fast and cannot be concurrently modified in a multi-threaded environment (modified during iteration).

2. Fail-Safe (fail—safe)

Collection containers that use the fail-safe mechanism do not directly access the collection contents during traversal; instead, they first copy the original collection contents and traverse the copied collection.

Principle:Since the iteration traverses a copy of the original collection, modifications made to the original collection during traversal cannot be detected by the iterator, so Concurrent Modification Exception will not be triggered.

> Disadvantages:The advantage of copying the contents is that it avoids Concurrent Modification Exception, but similarly, the iterator cannot access the modified contents. That is, the iterator traverses the collection copy obtained at the moment traversal began, and the iterator is unaware of modifications made to the original collection during traversal.

Scenarios:The containers under the java.util.concurrent package are all fail-safe and can be used concurrently and modified concurrently in a multi-threaded environment.

Original URL: http://www.cnblogs.com/ygj0930/p/6543350.html