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

HashMap merge and compute methods can cause odd resizing pathologies

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      Since the merge method will not call the resize method when the ++size exceeds the threshold, if the merge method is called in the forEach method at this time, the merge method will call the resize method, which will cause the forEach method to behave abnormally.


      ---------- BEGIN SOURCE ----------
      public class Main {
          public static void main(String[] args) {
              Map<Integer, Integer> map = new HashMap<>(2);

              map.merge(1, 1, Integer::sum);
              map.merge(2, 1, Integer::sum);

              map.forEach((k, v) -> {
                  map.merge(k, -1, Integer::sum);
                  System.out.println(k);
              });
          }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Same as the putVal method:
      if (++size > threshold) resize();

            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated: