JAVA Iterators (Fail Fast and Fail Safe)

Fail Fast and Fail Safe Explained Quoted from Niuke.com Q&A

https://www.nowcoder.com/questionTerminal/95e4f9fa513c4ef5bd6344cc3819d3f7?pos=101&mutiTagIds=570&orderByHotValue=1

One: fail-fast

          When traversing a collection object with an iterator, if the content of the collection object is modified (added, deleted, modified) during the traversal process, a Concurrent Modification Exception will be thrown.

          Principle: The iterator directly accesses the contents of the collection when traversing, and uses a modCount variable during the traversal. If the content of the collection changes while it is being traversed, the value of modCount will change. Whenever the iterator uses hashNext()/next() to traverse the next element, it will check whether the modCount variable is the expectedmodCount value, and if so, return the traversal; otherwise, throw an exception and terminate the traversal.

      Note: The throw condition of this exception is that modCount is detected! =expectedmodCount This condition. If the modified modCount value happens to be set to the expectedmodCount value when the collection changes, the exception will not be thrown. Therefore, the programming of concurrent operations cannot depend on whether this exception is thrown or not. This exception is only recommended for detecting concurrent modification bugs.

      Scenario: The collection classes in the java.util package are all fail-fast and cannot be concurrently modified (modified during iteration) under multiple threads.

    Two: fail-safe

      A collection container that adopts a failsafe mechanism does not directly access the collection content during traversal, but first copies the original collection content and traverses the copied collection.

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

      Disadvantages: The advantage of copying content is to avoid Concurrent Modification Exception , but in the same way, the iterator cannot access the modified content, that is: the iterator traverses the copy of the collection obtained at the moment of traversal, and the original copy during the traversal Modifications that occur to the collection are not known to the iterator.

          Scenario: The containers under the java.util.concurrent package are all safe to fail, and can be used and modified concurrently under multiple threads.

Example:



HashMap uses Iterator to modify the collection structure when traversing.

  public static Map HashMap() {
		  Map map=new HashMap();
          map.put("name", "张三");
          map.put("age", "15");
		  Iterator<Entry<String,String>> it=map.entrySet().iterator();
		  while(it.hasNext()) {
			  System.out.println(it.next().getValue());
			  map.remove("age");
		  }
		  return map;
	  }


ConcurrentHashMap uses Iterator to modify the collection structure when traversing.

	//Concurrent collection, when using Iterator to traverse the collection, there is no fast failure problem
	public static Map ConcurrentHashMap() {
	  ConcurrentHashMap<String,String> map=new ConcurrentHashMap<String,String>();
              map.put("name", "easy haha");
              map.put("age", "18");
              //keySet is a collection of keys, entrySet() collection of key-value pairs
               Iterator<Entry<String,String>> mapiterator= map.entrySet().iterator();
                while(mapiterator.hasNext()) {
                	System.out.println(mapiterator.next().getValue());
                	map.remove("name");//正常
                	
                }
                return map;
	}
	


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325750606&siteId=291194637