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

Replace simple iterations of Map.entrySet with Map.forEach calls

    XMLWordPrintable

Details

    Description

      A DESCRIPTION OF THE PROBLEM :
      In many cases in the JDK, such as Map implementation constructors or Map.putAll implementations, Map.entrySet is called to be simply iterated over without breaks.

      This is costly: Map.entrySet's iterator returns a new entry for each next call. This entry is an extra allocation, and would not be easily inlined even with valhalla, as it may refers to the parent map for its ability to update its value in setValue(). In contrast, the forEach call only allocates 1 lambda object for the whole loop.

      In addition, the simple for-loop iteration lacks guard against atomic access; for concurrent maps, regular iteration of entrySet may fail spontaneously; meanwhile, the forEach implementations of concurrent map handles such problems gracefully; see https://github.com/openjdk/jdk/blob/d7f31d0d53bfec627edc83ceb75fc6202891e186/src/java.base/share/classes/java/util/concurrent/ConcurrentMap.java#L118. A similar case I recall happened in string and string builder in the previous discussions, where functional is used not for performance, but for its safety in concurrency.

      This improvement is from https://github.com/openjdk/jdk/pull/7431#discussion_r810671760, in the discussion for the patch for JDK-8281631.


      Attachments

        Issue Links

          Activity

            People

              liach Chen Liang
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated: