Java Collection Quick Failure exception

Source: Internet
Author: User

Fast failure



in the JDK , there are many descriptions of quick failures in viewing collections:

Note that this implementation is not synchronous. If more than one thread accesses a hash map at the same time, and at least one of the threads modifies the mapping from the structure, it must remain externally synchronized. (Structural modification is any action that adds or deletes one or more mapping relationships; changing only the values associated with the key that the instance already contains are not structural modifications.) 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 map. It is a good idea to do this at creation time to prevent unintended non-synchronous access to the mappings, as follows:

Map m =collections.synchronizedmap (new HashMap (...)); The iterator returned by all such "collection View Methods" is a quick failure: After the iterator has been created, if the mapping is modified from the structure, the iterator will throw unless modified by the Remove method of the iterator itself, any other time, in any way. Concurrentmodificationexception. Therefore, in the face of concurrent modifications, the iterator will soon fail completely without risking any uncertain behavior at any time in the future.

Note that the fast failure behavior of iterators is not guaranteed and, in general, there is no firm guarantee that there is an asynchronous concurrent modification. The fast-failing iterator does its best to throw concurrentmodificationexception. Therefore, it is wrong to write a program that relies on this exception, and the correct approach is that the fast failure behavior of the iterator should only be used to detect program errors.


fast failure: for non-concurrent collections, when they are iterated, for example iterator when iterating, iterator is another thread, if there are other threads (such as Collection ) for structural modification (modifying the contents of the collection), this iteration immediately senses and immediately throws concurrentmodificationexception The exception, not the iteration, tells you that something went wrong, causing a quick failure. If modified with iterator , this problem will not occur, such as Iterator.move (); in other words, it involves synchronization between multiple threads .



Example code:

[Java] view plain copy

    1. Package Corejava;
    2. import Java.util.HashMap;
    3. import java.util.Hashtable;
    4. import java.util.Iterator;
    5. import Java.util.Map;
    6. import java.util.Map.Entry;
    7. import Java.util.concurrent.ConcurrentHashMap;

Public class Concurrenthashmaptest {

  1. Public static void main (string[] args) {
  2. 12.
  3. hashtable<string, string> table = new hashtable<string, string> ();
  4. Table.put ("A", "VB");
  5. Table.put ("s", "er");
  6. Table.put ("D", "FG");
  7. Table.remove ("D");
  8. iterator<entry<string, string>> Iterator = Table.entryset (). Iterator ();
  9. 19.
  10. while ( iterator.hasnext ()) {
  11. System.out.println (Iterator.next (). GetValue ());
  12. Iterator.remove ();//Use iterator directly to modify the program normal
  13. *//Table.put ("C", "WC"); Delete data directly from Hashtable error
  14. Table.remove ("D"), directly from the Hashtable add or delete data will be error hashtable,hashmap, such as non-concurrent sets if the iterative process of adding or subtracting data,
  15. 25.}
  16. 26.
  17. System.out.println ("-----------");
  18. 28.
  19. hashmap<string, string> HashMap = new hashmap<string, string> ();
  20. Hashmap.put ("A", "VB");
  21. Hashmap.put ("s", "er");
  22. Hashmap.put ("D", "FG");
  23. iterator<entry<string, string>> iterators = Hashmap.entryset ()
  24. Iterator ();
  25. 35.
  26. The. while (Iterators.hasnext ()) {
  27. Panax Notoginseng System.out.println (Iterators.next (). GetValue ());
  28. Iterators.remove ();//Normal
  29. *//Hashmap.remove ("D");//directly from the Hashtable add and delete data will be error hashtable,hashmap and other non-concurrent sets, if the iterative process of adding or subtracting data, will quickly fail (a change detected, immediately throw an exception)
  30. 40.}
  31. 41.
  32. System.out.println ("-----------");
  33. 43.
  34. concurrenthashmap<string, string> map = new concurrenthashmap<string, string> ();
  35. Map.put ("A", "VB");
  36. Map.put ("s", "er");
  37. Map.put ("D", "FG");
  38. iterator<entry<string, string>> mapiterator = Map.entryset (). Iterator ();
  39. 49.
  40. while ( mapiterator.hasnext ()) {
  41. Wuyi System.out.println (Mapiterator.next (). GetValue ());
  42. Map.Remove ("D");//Normal concurrent collection no quick failure problem
  43. Map.put ("C", "WC");//Normal concurrent collection no quick failure problem
  44. 54.}
  45. System.out.println ("-----------");
  46. . For (map.entry<string, string> entry:map.entrySet ()) {
  47. System.out.println (Entry.getvalue () + "," + Entry.getkey ());
  48. 58.}
  49. System.out.println ("-----------");
  50. For ( map.entry<string, string> entry:table.entrySet ()) {
  51. System.out.println (Entry.getvalue () + "," + Entry.getkey ());
  52. 62.}
  53. 63.}
  54. 64.
  55. 65./*
  56. * Final entry<k,v> NextEntry () {if (Modcount! = expectedmodcount) Throw
  57. * New Concurrentmodificationexception (); Entry<k,v> e = next; if (E = =
  58. * null) throw new Nosuchelementexception ();
  59. 69. *
  60. * if (next = e.next) = = null) {entry[] t = table; while (Index < t.length
  61. * && (next = t[index++]) = = null); } current = e; return e; }
  62. 72. */
  63. 73.

74.}

Fast Failure Exception: This exception is thrown when the method detects concurrent modifications to an object, but does not allow this modification

Workaround:

A: Iterator removal

B: Lock the gun back. The collection is self-deleted. (Premise: A collection of thread synchronizations)

Java Collection Quick Failure exception

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.