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

ConcurrentHashMap #size corrupted when using #computeIfPresent

    Details

      Description

      A DESCRIPTION OF THE PROBLEM :
      The documentation for #computeIfPresent states that if the remapping function returns null then that entry should be removed from the map, presumably decreasing the size of the map by 1. If this is done in a nested fashion where we invoke #computeIfPresent in the remapping function for the same key and return null the count decreases by 2, even though only one element ends up being removed.

      It might be worthy to note that this does not occur with java.util.HashMap.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      1. Add at least 2 entries to a ConcurrentHashMap
      2. Invoke #computeIfPresent with a remapping function that invokes #computeIfPresent and then returns null
      3. In the nested #computeIfPresent remapping function return null

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Since the map will have one entry removed, I expect the result of #size to have decreased by one.
      ACTUAL -
      The map's #size has decreased by two.

      ---------- BEGIN SOURCE ----------
      package com.company;

      import java.util.Map;
      import java.util.concurrent.ConcurrentHashMap;

      public class Main {
          public static void main(String[] args) {
              Map<String, String> map = new ConcurrentHashMap<>();
              map.put("1", "1");
              map.put("2", "2");

              printMap(map);

              map.computeIfPresent("1", (s, s2) -> {
                  map.computeIfPresent("1", (s1, s21) -> null);
                  return null;
              });

              printMap(map);
          }
          private static void printMap(Map<String, String> map) {
              System.out.println("Map size: [" + map.size() + "]");
              for (Map.Entry<String, String> entry : map.entrySet()) {
                  System.out.println(entry);
              }
          }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              webbuggrp Webbug Group
            • Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: