Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Fast failure and Security failure of Java Collection

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the Java collection of rapid failure and security failure example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Text fail-fast and fail-safe

Fail-fast Quick failure mechanism: a mechanism in the Java collection that throws a ConcurrentModificationException when traversing a collection object with an iterator, if the contents of the collection object are modified (added, deleted, modified) during traversal.

Fail-safe security failure mechanism: the containers under the java.util.concurrent package are all security failures, so they are not accessed directly on the collection content during traversal, but first copy the original collection content and traverse the copied collection, so the containers with security failure can be used concurrently under multi-thread and modified concurrently.

Fail-fast rapid failure mechanism public class test {public static void main (String [] args) {testForHashMap ();} private static void testForHashMap () {HashMap hashMap = new LinkedHashMap (); hashMap.put ("1", "a"); hashMap.put ("2", "b"); hashMap.put ("3", "c"); Iterator iterator=hashMap.entrySet () .iterator () While (iterator.hasNext ()) {hashMap.put ("bloom", "bloom"); System.out.println (iterator.next ());}}

Quick failure is triggered by modifying collection elements under the fast failure mechanism, and the output is as follows:

When traversing the collection, adding or deleting elements will throw a ConcurrentModificationException exception

Fail-safe security failure mechanism public class test {public static void main (String [] args) {testForHashTable ();} private static void testForHashTable () {Hashtable hashtable = new Hashtable (); hashtable.put ("4", "d"); hashtable.put ("5", "e"); hashtable.put ("6", "f"); Enumeration iterator1=hashtable.elements () While (iterator1.hasMoreElements ()) {hashtable.put ("bloom", "bloom"); System.out.println (iterator1.nextElement ());}}

Modify the collection elements and output the results under the security failure mechanism

We can add and delete elements while traversing the collection

Make a brief summary

Fail-fast, which is an error detection mechanism for Java collections.

When traversing a collection object with an iterator, if the contents of the collection object should not be modified (add, delete, modify) during traversal, you can create a new collection to operate on.

Quick failure & Security failure (most comprehensive summary) public static void main (String [] args) {Hashtable table = new Hashtable (); table.put ("a", "aa"); table.put ("b", "bb"); table.put ("c", "cc"); table.remove ("c"); Iterator iterator = table.entrySet (). Iterator (); while (iterator.hasNext ()) {System.out.println (iterator.next (). GetValue ()) / / use iterator to modify the program directly iterator.remove (); / / add and delete data directly from hashtable will report error table.put ("d", "dd"); / / add and delete data directly from hashtable will report error, hashtable,hashmap and other non-concurrent collections. If you add or subtract data in the iterative process, it is a rapid failure table.remove ("c");} System.out.println ("-"). Lock lock = new ReentrantLock (); / / even with lock, ConcurrentModificationException exception lock.lock (); HashMap hashmap = new HashMap (); hashmap.put ("a", "aa"); hashmap.put ("b", "bb"); hashmap.put ("c", "cc"); Iterator iterators = hashmap.entrySet (). Iterator (); while (iterators.hasNext ()) {System.out.println (iterators.next (). GetValue ()); / / normal iterators.remove () / / if you add or delete data directly from hashtable, an error will be reported. Non-concurrent collections such as / hashtable,hashmap will fail quickly (throw an exception as soon as a change is detected) / / java.util.ConcurrentModificationExceptionhashmap.remove ("c");} System.out.println ("-"); lock.unlock (); ConcurrentHashMap map = new ConcurrentHashMap (); map.put ("a", "aa"); map.put ("b", "bb") if the data is added or subtracted during the iteration. Map.put ("c", "cc"); Iterator mapiterator = map.entrySet (). Iterator (); while (mapiterator.hasNext ()) {System.out.println (mapiterator.next (). GetValue ()); map.remove ("c"); / / there is no quick failure problem in normal concurrent sets map.put ("c", "cc") / / there is no problem of fast failure in normal concurrent collections} System.out.println ("-");}

Running this code shows that if you make a "modify" operation on the container object during the loop iteration of Hashtable and HashMap, you will run out of java.util.ConcurrentModificationException exception, and the operation on Iterator will not be abnormal. But ConcurrentHashMap doesn't throw exceptions on both container objects and Iterator objects. Why?

(1) first, let's introduce two concepts, quick failure and security failure.

The security failure of Iterator is based on copying the underlying collection, so it is not affected by changes on the source collection. All the collection classes under the java.util package fail quickly, while all the classes under the java.util.concurrent package fail securely.

A fast-failing iterator throws a ConcurrentModificationException exception, while a security-failed iterator never throws such an exception.

(2) when we look at the entrySet objects of Hashtable, HashMap, and ConcurrentHashMap at the bottom of Java API, we find that all three have made copies of the current objects, and they are handled in the same way, so what's the difference? Look at the logical difference in getting the next entrySet

This is Hashtable, HashMap's.

Final Node nextNode () {Node [] t; Node e = next; if (modCount! = expectedModCount) throw new ConcurrentModificationException (); if (e = = null) throw new NoSuchElementException (); if ((next = (current = e) .next) = null & & (t = table)! = null) {do {} while (index

< t.length && (next = t[index++]) == null); } return e; } 这是ConcurrentHashMap的 public final Map.Entry next() { Node p; if ((p = next) == null) throw new NoSuchElementException(); K k = p.key; V v = p.val; lastReturned = p; advance(); return new MapEntry(k, v, map); }/** * Advances if possible, returning next valid node, or null if none. */ final Node advance() { Node e; if ((e = next) != null) e = e.next; for (;;) { Node[] t; int i, n; // must use locals in checks if (e != null) return next = e; if (baseIndex >

= baseLimit | | (t = tab) = = null | | (n = t.length) = n) index = + + baseIndex; / / visit upper slots if present}}

Iterators in ConcurrentHashMap mainly include entrySet, keySet, and values methods. They are more or less the same, entrySet explanation is chosen here. When we call the iterator method of the entrySet return value, we return EntryIterator, and when we call the next method on EntryIterator, we end up actually calling the HashIterator.advance () method. This method traverses the underlying array.

During traversal, the iterator does not throw a ConcurrentModificationException exception if the contents of the array that has been traversed have changed. If the content on the untraversed array changes, it may be reflected in the iteration process.

This is the manifestation of the weak consistency of ConcurrentHashMap iterators. The weak consistency of ConcurrentHashMap is mainly to improve efficiency, which is a tradeoff between consistency and efficiency. To be highly consistent, you have to use locks everywhere, even global locks, just like Hashtable and synchronized HashMap.

Finally, let's take a look at the description of fast failure in JDK:

Note that this implementation is not synchronous. If multiple threads access a hash map at the same time, and at least one of them modifies the mapping structurally, it must maintain external synchronization. A structural modification is any operation that adds or removes one or more mapping relationships; changing only the values associated with the keys already contained in the instance is not a structural modification. This is typically done by synchronizing the objects that naturally encapsulate the mapping

If such an object does not exist, you should use the Collections.synchronizedMap method to "wrap" the mapping. It is best to do this at creation time to prevent unexpected asynchronous access to the map, as follows: Map m = Collections.synchronizedMap (new HashMap (...)) The iterators returned by all such "collection view methods" fail quickly: after the iterator is created, if the mapping is structurally modified, the iterator will throw a ConcurrentModificationException except through the iterator's own remove method. Therefore, in the face of concurrent changes, the iterator will soon fail completely without risking arbitrary uncertain behavior at an uncertain time in the future.

Note that the fast failure behavior of iterators cannot be guaranteed, and in general, it is impossible to make any firm guarantees when there are asynchronous concurrent modifications. The quick failure iterator does its best to throw the ConcurrentModificationException. Therefore, it is wrong to write programs that rely on this exception, and the right thing to do is that the quick failure behavior of iterators should only be used to detect program errors.

Thank you for reading this article carefully. I hope the article "sample Analysis of Java Collection Rapid failure and Security failure" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report