Easy Tutorial
❮ 8 Awesome Awk Built In Variables Most Popular Javascript Code Specifications ❯

Java's Fail-Fast and Fail-Safe Mechanisms

Category Programming Techniques

I. Fail-Fast

When iterating over a collection object, if the content of the collection is modified during the iteration (added, deleted, modified), a Concurrent Modification Exception will be thrown.

Principle: The iterator accesses the content of the collection directly during iteration and uses a modCount variable during the process. If the content of the collection changes while being iterated, the value of modCount will change. Before the iterator uses hashNext()/next() to iterate to the next element, it checks whether the modCount variable is equal to the expectedmodCount value. If it is, it continues the iteration; otherwise, it throws an exception and terminates the iteration.

Note: The condition for throwing this exception is when modCount != expectedmodCount is detected. If the modCount value is modified to the expectedmodCount value exactly when the collection changes, the exception will not be thrown. Therefore, do not rely on whether this exception is thrown to program concurrent operations; this exception is only recommended for detecting bugs in concurrent modifications.

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

II. Fail-Safe

Collection containers that use the fail-safe mechanism do not access the collection content directly during iteration; instead, they first copy the original collection content and iterate over the copied collection.

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

Disadvantage: The advantage of being based on copied content is that it avoids Concurrent Modification Exception, but at the same time, the iterator cannot access the modified content, that is: the iterator iterates over the collection copy obtained at the moment of starting the iteration, and the modifications made to the original collection during the iteration are unknown to the iterator.

Scenario: The containers under the java.util.concurrent package are fail-safe and can be used concurrently in a multi-threaded environment, with concurrent modifications.

>

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

** Share my notes

Cancel

-

-

-

❮ 8 Awesome Awk Built In Variables Most Popular Javascript Code Specifications ❯