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

Omit enclosing instance fields from inner classes that don't use it

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P3 P3
    • 18
    • None
    • tools
    • b26

      When translating an inner class, javac emits a synthetic field to hold the reference to the enclosing instance. The field is emitted even if there are no references to enclosing instance state in the inner class. This can cause memory leaks, e.g. when anonymous classes are created as listeners and accidentally capture enclosing instance state that is not intended to be long-lived.

      The proposed enhancement is for javac to omit the reference to the enclosing instance when translating inner classes that don't capture any enclosing instance state.

      That is, given

      class T {
        class I {
        }
      }

      before:

      {
        final T this$0;
          descriptor: LT;
          flags: (0x1010) ACC_FINAL, ACC_SYNTHETIC

        T$I(T);
          descriptor: (LT;)V
          flags: (0x0000)
          Code:
            stack=2, locals=2, args_size=2
               0: aload_0
               1: aload_1
               2: putfield #1 // Field this$0:LT;
               5: aload_0
               6: invokespecial #2 // Method java/lang/Object."<init>":()V
               9: return
            LineNumberTable:
              line 2: 0
      }

      after:

      {
        T$I(T);
          descriptor: (LT;)V
          flags: (0x0000)
          Code:
            stack=1, locals=2, args_size=2
               0: aload_0
               1: invokespecial #1 // Method java/lang/Object."<init>":()V
               4: return
            LineNumberTable:
              line 2: 0
      }

      Related discussion:

      * https://bugs.openjdk.java.net/browse/JDK-6324535?focusedCommentId=12265883&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-12265883
      * https://mail.openjdk.java.net/pipermail/amber-spec-experts/2021-July/003061.html
      * https://mail.openjdk.java.net/pipermail/amber-spec-experts/2021-July/003062.html
      * https://mail.openjdk.java.net/pipermail/amber-spec-experts/2021-August/003065.html
      * https://mail.openjdk.java.net/pipermail/amber-spec-experts/2021-August/003066.html

            cushon Liam Miller-Cushon
            cushon Liam Miller-Cushon
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: