Java Iterator fail-fast mechanism

Source: Internet
Author: User

Fail-fast: When the data is changed in the iterative process, it throws an exception immediately, instead of having to throw an exception after it has been traversed, which can be understood as rapid perception.

In concurrency, when thread A is traversing a collection or map, and another thread B modifies collection or map, thread A throws an error: Concurrentmodificationexception.

Even if it is run in a single thread, the java.util.ConcurrentModificationException exception will be thrown.

Indicates: What I am reading is modified, do you need to re-traverse? Or do any other processing? This is the meaning of fail-fast.

map<integer, string> Map = new hashmap<> (); Map.put (1, "a"); Map.put ( 2, "a");iterator<integer> keys = Map.keyset (). Iterator (); while (Keys.hasnext ()) {Integer i = 0;try {i = Keys.next ();  System.out.println ("Before Remove:" +map.size ());/** * Removes from the underlying collection The last element returned by  This iterator (optional operation).  * This method can is called only once per call to next (). * The behavior of an iterator is unspecified if the underlying collection are modified while the iteration * are in Progres s in any-to-than by calling this method. * *///keys.remove (); Map.Remove (i); System.out.println ("Remove Running:" +map.size ());} catch (Concurrentmodificationexception e) {System.out.println (e.tostring ()); System.exit (0);} 

When you try to modify the contents of Collection/map directly while using Fail-fast iterator to iterate over the Collection or MAP, even if you are running in a single thread, JAVA.UTIL.CONCURRENTMODIF Icationexception exceptions will also be thrown.  

Iterator is working in a separate thread and has a mutex lock. Iterator is created after the creation of a single-chain index table pointing to the original object, when the original object number changes, the contents of the index table will not be synchronized changes, so when the index pointer moves back to find the object to iterate, so according to Fail-fast principle Iterator The java.util.ConcurrentModificationException exception is thrown immediately. &NBSP

So Iterator is not allowed to be iterated at the time of the work. But you can delete the object using Iterator's own method, remove (), and the Iterator.remove () method maintains the consistency of the index while deleting the current iteration object.  

Interestingly, if your Collection/map object actually has only one element, the concurrentmodificationexception exception is not thrown. This is why it is stated in Javadoc that: it would is wrong to the write a program, the depended on the exception for its correctness:concurren Tmodificationexception should is used only to detect bugs. 

The collection classes in the

 java.util package return fail-fast iterators, which means that they assume that the collection does not change its contents when the thread iterates through the contents of the collection. If the Fail-fast iterator detects that a change was made during the iteration, it throws Concurrentmodificationexception, which is an uncontrolled exception.  
      not changing the requirements of a collection during the iteration often causes inconvenience to many concurrent applications. Conversely, it is better to allow concurrent modifications and to ensure that iterators can provide a consistent view of the collection as long as they are properly manipulated, as is done by iterators in the Java.util.concurrent collection class.   The iterator returned by the
     java.util.concurrent collection is called a weakly consistent (weakly consistent) iterator. For these classes, if the element has been deleted since the iteration and has not yet been returned by the next () method, it will not be returned to the caller. If an element has been added since the iteration began, it may or may not return the caller. In one iteration, regardless of the underlying collection, the element is not returned two times.

Fail-fast is a specific application of the optimistic (optimistic) strategy in concurrency, which allows threads to free competition, but in the event of a conflict it is assumed that you can handle it, that is, you can determine what the problem is and give a solution. The pessimistic (pessimistic) strategy is just the opposite, it always pre-sets enough limits, usually with a lock , to ensure that the program is in the process of error-free, paying the cost is the waiting cost of other threads:  

Vector v = ...; Synchronized (v) {Listiterator iter = V.listiterator (); while (Iter.hasnext ()) {Object o = Iter.next ();//do something ...}}

  

As you can see, this traversal process is synchronized, of course, no other thread can modify V ( even if the Vector itself is synchronous ), there will never be confusion, unpredictable results. But if this synchronization block is a frequently called module, then the other threads waiting time will not be a small number, when it is a single-threaded system, can see the CPU processing capacity:)

Doug LeaOfConcurrentPackage gives another solution,Copy on Write。 It'scopyonwritearraylist、Copyonwritearraysetwill be threadBWhen attempting to modify a data container, give acopy container < Span style= "font-family:"times New roman"" ( of course, our program is not felt " , so the thread a in the old version of v On traversal, thread b in the new version of the v modified, both irrelevant and never appear concurrentmodificationexception 。 Its cost is mainly in the container of copy , when the higher the degree of concurrency, The more expensive it is.

Therefore,one of the basic prerequisites forFast Fail to be introduced to the JDK is that most of your situations are simply traversing a collection, and no other thread will do it update. In this way, its efficiency is the most sufficient. But if you are constantly encountering concurrentmodificationexception Anomalies, consider whether you want to perform a certain number of re-traversal or simply use pessimistic policies to lock resources to ensure thread safety.

Java Iterator fail-fast mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.