Java.util.ConcurrentModificationException anomaly Solution and principle (top)

Source: Internet
Author: User

A recent bug in the fix found that the following exception was thrown by the background:

Exception in thread ' main ' java.util.ConcurrentModificationException at
  java.util.hashmap$ Hashiterator.nextentry (hashmap.java:793) at
  java.util.hashmap$keyiterator.next (hashmap.java:828)
  at COM.KEYMAN.DEMO.TEST.CLEARRESULTTABLE.METHOD2 (clearresulttable.java:54) at
  Com.keyman.demo.test.ClearResultTable.main (clearresulttable.java:88)

Found the error line: at COM.KEYMAN.DEMO.TEST.CLEARRESULTTABLE.METHOD2 (clearresulttable.java:54) found, error location: for (String s1:sets)

set<string> sets = Map.keyset ();
    for (string s1:sets) {
      String value = Map.get (S1);
      Deletes a key value pair that satisfies the value with ABC (
      Value.startswith ("abc")) {
        map.remove (S1);
      }
    

Or the following method throws an exception

Iterator<string> iterator = Map.keyset (). iterator ();
    while (Iterator.hasnext ()) {
      String key = Iterator.next ();
      String value = Map.get (key);
      Deletes a key-value pair
      if (Value.startswith ("abc")) {
        Map.Remove (key) that satisfies the value with ABC; 
        Iterator.remove (); Sync modcount and Expectedmodcount
        
      }
    }

Actually, whatever.

This exception is thrown when the Map or Set is in operation.

The solution is: if the iteration is not iterator, then the map iteration is modified in iterator () mode, with Iterator.remove () instead of directly through Map.Remove ();

Iterator<string> iterator = Map.keyset (). iterator ();
    while (Iterator.hasnext ()) {
      String key = Iterator.next ();
      String value = Map.get (key);
      Deletes a key-value pair
      if (Value.startswith ("abc")) {
        //map.remove (value) that satisfies the value with ABC; 
        Iterator.remove ();   Critical code, synchronizing Modcount and Expectedmodcount
        
      }
    }

Detailed reasons are as follows:

Found that this position should not be an error, find contextual, found that the most likely error should be for the loop inside, but I look at all right. By looking for data discovery: This exception is thrown when the number of modifications is not equal to the number of expected modifications.

Private abstract class Hashiterator<e> implements iterator<e> {
  entry<k, v> next;//next Entry to R Eturn
  int expectedmodcount;//for fast-fail
  int index;//current slot
  entry<k, v> current; Entry ...
  Final entry<k, v> nextentry () {
    if (modcount!= expectedmodcount)
      throw new Concurrentmodificationexception (); Throws an exception
    entry<k, v> e = current = next;
    if (E = = null)
      throw new Nosuchelementexception ();

    if (next = e.next) = = null) {
      entry[] t = table;
      while (Index < t.length && (next = t[index++]) = = null
        )
    ;
    return e;
  }
  ...
}

So look at the Hashmap.remove () method code as follows:

/** * Removes the mapping for the specified key from this map if present. * * @param key key whose mapping is to removed from the map * @return The previous value associated with <tt&
   Gt;key</tt>, or * <tt>null</tt> if there is no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate the map * previously associated <tt>null</tt& Gt
   with <tt>key</tt>.)
    */Public V Remove (Object key) {entry<k,v> E = Removeentryforkey (key);
  return (E = null null:e.value);  }/** * Removes and returns the entry associated with the specified key * in the HASHMAP.
   Returns NULL if the HASHMAP contains no mapping * for this key.
    * * Final entry<k,v> Removeentryforkey (Object key) {int hash = (key = = null)? 0:hash (Key.hashcode ());
    int i = indexfor (hash, table.length);
    Entry<k,v> prev = table[i];
entry<k,v> e = prev;
    while (e!= null) {entry<k,v> next = E.next;
      Object K; if (E.hash = = Hash && (k = e.key) = = Key | | (Key!= null && key.equals (k)))
        {modcount++;
        size--;
        if (prev = = e) Table[i] = next;
        else Prev.next = next;
        E.recordremoval (this);
      return e;
      } prev = e;
    e = next;
  return e; }

You will find that there are modcount++ operations.

Modcount said the number of changes, and did not change their exceptedmodcount;

Next look at the Iterator.remove () method: (Java.util.Hashtable.Enumerator.remove ())

public void Remove () {if (!iterator) throw new Unsupportedoperationexception ();
      if (lastreturned = = null) throw new IllegalStateException ("Hashtable enumerator");

      if (Modcount!= expectedmodcount) throw new Concurrentmodificationexception ();
    Synchronized (hashtable.this) {entry[] tab = Hashtable.this.table;

    int index = (lastreturned.hash & 0x7fffffff)% Tab.length;
         for (entry<k,v> e = Tab[index], prev = null; e!= null;
      Prev = e, E = E.next) {if (E = = lastreturned) {modcount++;
      expectedmodcount++;
      if (prev = = null) Tab[index] = E.next;
      else Prev.next = E.next;
      count--;
      lastreturned = null;
        Return
      } throw new Concurrentmodificationexception (); }
  }
    }

This method of deleting the element will increase the modcount of the Exceptedmodcount as well as its own. It will not throw an exception.


Reproduced in: Http://www.tuicool.com/articles/MbyMra

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.