The fail-fast mechanism is an error mechanism in the Java Collection (Collection). Fail-fast events can occur when multiple threads operate on the contents of the same collection. For example, when a thread a passes through a iterator to traverse a collection, if the content of the collection is changed by another thread, then thread a accesses the collection and throws a Concurrentmodificationexception exception to produce the Fail-fast event.
The fail-fast mechanism is an error mechanism in the Java Collection (Collection). Fail-fast events can occur when multiple threads operate on the contents of the same collection.
For example, when a thread a passes through a iterator to traverse a collection, if the content of the collection is changed by another thread, then thread a accesses the collection and throws a Concurrentmodificationexception exception to produce the Fail-fast event.
To understand the fail-fast mechanism, we must first understand the concurrentmodificationexception anomaly. This exception is thrown when the method detects concurrent modifications to the object, but does not allow this modification. Also note that the exception does not always indicate that the object has been modified concurrently by a different thread, and that if a single thread violates the rule, it is also possible to throw a modification exception.
Admittedly, the rapid failure behavior of the iterator is not guaranteed, it does not guarantee that the error will occur, but the fast fail operation will do its best to throw the concurrentmodificationexception exception, so It is an error to write a program that relies on this exception to improve the correctness of this type of operation: Concurrentmodificationexception should only be used to detect bugs.
The iterator in Java makes it easy to provide a uniform data-reading (delete) interface for all data sources, but novice users often report the following error concurrentmodificationexception when they use it. The reason is that the underlying data is modified when using an iterator, most often in a data source that is not a thread-safe class, such as HashMap & ArrayList.
Why should there be fast-fail
a case
An example of a novice who is apt to err:
String[] Stringarray = {"A", "B", "C", "D"};
List<string> strings = Arrays.aslist (Stringarray);
Iterator<string> iterator = Strings.iterator ();
while (Iterator.hasnext ()) {
if (Iterator.next (). Equals ("C")) {
strings.remove ("C");
}
}
More commonly, in the case of foreach (essentially, when iterator is invoked, the original strings) statement is manipulated:
for (String s:strings) {
if (s.equals ("C")) {
strings.remove ("C");
}
}
Cause
the collection class (data source) in Java is divided into two types: thread-safe, in the java.util.concurrent named directory, such as copyonwritearraylist; thread unsafe: Located in Java.util directory, such as Arraylist,hashmap. The so-called thread safety is in the multithreaded environment, this class also can show and behavior specification consistent result, whether genteel ... Google it yourself.
So why do we have to have ArrayList, since we can make a collection of wired safe alternatives? Because thread-safe classes often need to maintain synchronization of data access through a variety of means, they are generally less efficient. However, if the user knows that there is no concurrent scenario for their own use of the scene, then using a thread-safe collection class has great advantage in speed.
If the developer is not aware of the use, the thread-safe collection class is used in concurrent scenarios, for example, thread A acquires the ArrayList iterator, then thread B modifies the ArrayList data by invoking Arraylist.add (). At this point it is possible to throw concurrentmodificationexception, note that this is possible. So why is this error reported in the above example? The above does not exist concurrent situation, hug one eye the source code bar.
Iterator Source Analysis
the Fast-fail implementation in the collection class is similar, let's take the simplest ArrayList as an example.
A variable is held in the ArrayList, declared as:
protected transient int modcount = 0; records the number of times we modified the ArrayList, such as when we call Add (), remove (), and so on, we will modcount++.
We return through Arraylist.iterator () a arraylistiterator that implements the iterator interface:
Private class Arraylistiterator implements Iterator<e> {
//Omit part of code ...
. When initializing, directly to Expectedmodcount assign ArrayList the number of changes
private int expectedmodcount = Modcount;
@SuppressWarnings ("unchecked") public E Next () {
...
.. arraylist<e> ourlist = arraylist.this;
A simple comparison of the current iterator initialization when the value of Arraylist.modcount
//and current values are consistent, if not equal, think after the current iterator has been acquired
//different position (possibly other threads) Modified ArrayList, direct throw exception
if (Ourlist.modcount!= expectedmodcount) {
throw new concurrentmodificationexception () ;
}
............
}
}
The principle is very simple, when building iterator the current ArrayList of the Modcount save up, each time next (), to determine whether the Modcount value of ArrayList changes, if there is, in the process of the code changed the data (mentioned above, Only call Add () remove () to modify the value of the Modcount.
This also explains why in the example we are not concurrent scenes also error, because we call Arraylist.remove () changed the value of the Modcount.
But how much does this thing mean? It seems to me to be a bit of an superfluous suspicion. Because in a real concurrency scenario, this fast-fail mechanism does not really even find another thread to access and modify the data in ArrayList. The reasons are as follows:
Then look at the definition of modcount protected transient int modcount = 0;. You are not mistaken, it is a common variable, then in the concurrent scenario due to the invisibility of the shared object, it is possible that other threads have modified the Modcount in the ArrayList, while iterator's thread has not read the update. HashMap did use volatile to modify the modcount to ensure that each thread was directly visible to Modcount, but in 1.7 it was removed and considered a bug--> Java7 Remove Volatitle, sad ah ... The reason is that JDK developers think it's wasteful to use volatitle for such a mess.
Even if the use of Volatitle is Bob? Nono, for the simplest example, thread A gets the iterator of a collection class, thread B calls the Add () of the collection class, and when add () is not yet executed to modcount++, thread A gets execution and executes the end. In this scenario, the execution results are not determined. For ArrayList's iterator, it is possible to quote an array of exceptions that are out of bounds ...
Summarize
Fast-fail is the JDK. To prompt the developer to use a thread-safe class in a concurrent scenario, throw an exception and discover the problem in the code early. But as noted earlier in this article, this mechanism does not give an absolutely correct hint, and the old JDK version pays a certain cost of efficiency in order to better support this mechanism.
The only value of Fast-fail's existence may be to create some confusion for the novice, to give him the impetus to further explore ... Hey
Add:
A lot of data on the internet said that when using iterator can not be modified, so it is not completely accurate. Even the iterator itself, which supports Fast-fail, also provides remove () to delete the currently traversed element, for example, remove () in the Arraylistiterator, and the chestnuts above are changed to read as follows:
while (Iterator.hasnext ()) {
if (Iterator.next (). Equals ("C")) {
iterator.remove ("C");
}
}