< prev index next >

test/jdk/java/util/concurrent/ConcurrentMap/ConcurrentModification.java

Print this page
rev 54324 : Test hashmap.clear concurrent modification

@@ -25,10 +25,12 @@
  * @test
  * @bug 6312056 4155650 4294891 4904074
  * @summary Reasonable things should happen if mutating while iterating.
  */
 
+import java.util.ConcurrentModificationException;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ConcurrentSkipListMap;

@@ -89,13 +91,75 @@
                 }
             }
         } catch (Throwable t) {unexpected(t);}
     }
 
+    // expected java.util.ConcurrentModificationException
+    static void expected(Throwable t) {
+        if (t instanceof ConcurrentModificationException)
+            passed++;
+        else {
+            failed++;
+            t.printStackTrace();
+        }
+    }
+    private static void testClear(HashMap<Integer, Integer> m) {
+        try {
+            // modifying an empty map expects no ConcurrentModificationException
+            m.clear();
+            check(m.isEmpty());
+            m.computeIfAbsent(null, key -> {
+                m.clear();
+                return null;
+            });
+        } catch (Throwable t) {
+            unexpected(t);
+        }
+
+        try {
+            // modifying an empty map expects no ConcurrentModificationException
+            m.clear();
+            check(m.isEmpty());
+            m.compute(null, (key, value) -> {
+                m.clear();
+                return null;
+            });
+        } catch (Throwable t) {
+            unexpected(t);
+        }
+
+        try {
+            // modifying an empty map expects no ConcurrentModificationException
+            m.clear();
+            m.put(1, 2);
+            check(!m.isEmpty());
+            m.computeIfAbsent(null, key -> {
+                m.clear();
+                return null;
+            });
+        } catch (Throwable t) {
+            expected(t);
+        }
+
+        try {
+            // modifying an empty map expects no ConcurrentModificationException
+            m.clear();
+            m.put(1, 2);
+            check(!m.isEmpty());
+            m.compute(null, (key, value) -> {
+                m.clear();
+                return null;
+            });
+        } catch (Throwable t) {
+            expected(t);
+        }
+    }
+
     public static void main(String[] args) {
         test(new ConcurrentHashMap<Integer,Integer>());
         test(new ConcurrentSkipListMap<Integer,Integer>());
+        testClear(new HashMap<Integer, Integer>());
 
         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
         if (failed > 0) throw new Error("Some tests failed");
     }
 }
< prev index next >