Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8222394

HashMap clear does ++modCount unconditionally, so do compute/computeIfAbsent throw CME



    • Type: Bug
    • Status: Closed
    • Priority: P4
    • Resolution: Won't Fix
    • Affects Version/s: 13
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:


      Firstly this is a tricky case triggered in my testing farm. I found it with one of my aarch64 system (Ampere) and have finally proven it as a common problem with a small and "sneaky" case.

      Here is the original post:
      Some updates:

      It is known that HashMap does not support concurrent access, but would be responsible of throwing CME "on a best-effort basis" if a potential concurrent modification is detected.

      Here is my test case, [0] creates a HashMap, keeps it empty, and calls m.computeIfAbsent() or m.compute(), in which a "sneaky" m.clear() occurs, some of the test cases throw CME although there were no "structural" changes in fact. (A structural modification is defined as "any operation that adds or deletes one or more mappings...").

      jdk8u cannot reproduce this issue, but jdk9 and beyond can, since the bug [1] got fixed for computeIfAbsent() concurrent co-modification issues. A couple of test cases [2] were introduced at that time, and the focus was to verify the behaviors at resizing, while empty maps were not tested.

      A possible "fix" for this issue is to move the unconditional "modCount++" [3] into the if-clause, which indicates that a "structural" change would be happening indeed.

      public void clear() {
          Node<K,V>[] tab;
      - modCount++;
          if ((tab = table) != null && size > 0) {
      + modCount++;
                size = 0;
                for (int i = 0; i < tab.length; ++i)
                  tab[i] = null;

      Therefore, a dilemma here is "modCount++ before-if-clause but overkills some cases" vs. "modCount++ into-if-clause but weakens the CME checking potentially". I want to make a more reasonable balance regarding how to "throw CME on a best-effort basis" more appropriately. Any suggestion?

      I understand that CME here in HashMap.java cannot guarantee much and may be only for debugging purpose, any concurrent modification needs to be typically accomplished by synchronizing on some object that naturally encapsulates the map. So the mentioned issue is a just a tricky case.



          Issue Links



              qpzhang Patrick Zhang
              qpzhang Patrick Zhang
              0 Vote for this issue
              3 Start watching this issue