HashMap is not synchronized, why the exception of parallel modification

HashMap does not have to be thread safe, then why iterators throw concurrentmodificationexceptionif someone changed hashMap.

Also, ConcurrentHashMap does not throw this exception.

Is the Iterator implementation different for different data structures or is there someone method in these data structures that throw concurrentmodificationexception

+4
source share
4 answers

When structure a HashMapchanges (that is, records are added or deleted) while iteration HashMapis performed, the iterator can fail in many ways.

ConcurrentModificationException , .

modCount :

/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
transient int modCount;

Map s. Collection , .

+3

, Concurrent .

, , , . , , .

CME:

Map<String, String> map = new HashMap<>();
map.put("a", "a");
map.put("b", "b");

for (String k: map.entrySet()) {
  map.clear();
}

, ( ):

Iterator<String> it = map.entrySet().iterator();
while (it.hasNext()) {
  String k = it.next();
  map.clear();
}

it.hasNext() map.clear(), ConcurrentModificationException.

+3

- , ConcurrentModificationException?

, Iterator Collection.

, HashMap class ( HashIterator ), ConcurrentHashMap ( KeyIterator, ValueIterator .. ), ArrayList ( Iterator AbstractList) ..

HashMap Iterator ConcurrentHashMap.

HashMap (expectedModCount) checkForComodification(), :

final void checkForComodification() {
   if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

, , (/ ), Iterator throw ConcurrentModificationException, .

ConcurrentHashMap Iterator , ConcurrentModificationException. API ConcurrentHashMap .

(ConcurrentHashMaps) ConcurrentModificationException. .

0

HashMap ( java.util ), Iterator Throws, - Hashmap.

Hashmap, Map.and, , .

transient volatile int modCount;

Read the following link: The difference is explained very well: Java Modcount (ArrayList) Good example: http://www.journaldev.com/122/java-concurrenthashmap-example-iterator

0
source

Source: https://habr.com/ru/post/1662376/


All Articles