< prev index next >

src/java.base/share/classes/java/util/HashMap.java

Print this page
rev 54472 : 8222394: HashMap.clear do ++modCount unconditionally

@@ -855,10 +855,12 @@
      * Removes all of the mappings from this map.
      * The map will be empty after this call returns.
      */
     public void clear() {
         Node<K,V>[] tab;
+        // Increase this counter unconditionally in order to warn concurrent
+        // modifications more defensiblly
         modCount++;
         if ((tab = table) != null && size > 0) {
             size = 0;
             for (int i = 0; i < tab.length; ++i)
                 tab[i] = null;

@@ -1134,11 +1136,14 @@
                 return oldValue;
             }
         }
         int mc = modCount;
         V v = mappingFunction.apply(key);
-        if (mc != modCount) { throw new ConcurrentModificationException(); }
+        // Not to throw CME if mappingFunction has no practical impact on the map
+        if (v != null && mc != modCount) {
+            throw new ConcurrentModificationException();
+        }
         if (v == null) {
             return null;
         } else if (old != null) {
             old.value = v;
             afterNodeAccess(old);

@@ -1229,11 +1234,14 @@
             }
         }
         V oldValue = (old == null) ? null : old.value;
         int mc = modCount;
         V v = remappingFunction.apply(key, oldValue);
-        if (mc != modCount) { throw new ConcurrentModificationException(); }
+        // Not to throw CME if remappingFunction has no practical impact on the map
+        if ((old != null || v != null) && mc != modCount) {
+            throw new ConcurrentModificationException();
+        }
         if (old != null) {
             if (v != null) {
                 old.value = v;
                 afterNodeAccess(old);
             }
< prev index next >