RFR: 8315850: Improve AbstractMap anonymous Iterator classes

Stuart Marks smarks at openjdk.org
Thu Sep 7 18:08:37 UTC 2023


On Thu, 7 Sep 2023 12:24:58 GMT, Rémi Forax <forax at openjdk.org> wrote:

>> This PR proposes to slightly improve some iterators of `AbstractMap`:
>> 
>> * Code reuse
>> * A field declared `final`
>> * Add missing `@Override` annotations
>
> Hello,
> In Java, sharing code may have a runtime cost (or not) depending on the shape of the code, because the VM may have to speculate on the class of some value at runtime.
> Here, in hasNext() and remove(), the VM has to find the class of the field 'i' at runtime.
> 
> Iterators are performance sentive (they are used in for loop) and for that they need the escape analysis to work.
> If the iterator code is polymorphic, so part of the code may be unknown so the escape analysis will consider that the iterator escape. So usually, it's a good practice to not share the iterator code.
> 
> Also the field should be package private (or even maybe private) but not protected. Protected is very rare in Java because usually classes that share implementation details are in the same package (or in the same nestmate nest).

@forax Note that HashMap uses a similar subclassing idiom for the iterators of the keySet, values, and entrySet collections in order to share the iterator logic:

https://github.com/openjdk/jdk/blob/jdk-21%2B35/src/java.base/share/classes/java/util/HashMap.java#L1626

-------------

PR Comment: https://git.openjdk.org/jdk/pull/15615#issuecomment-1710574566


More information about the core-libs-dev mailing list