Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8271623 Omit enclosing instance fields from inner classes that don't use it
  3. JDK-8277604

Release Note: Enclosing Instance Fields Omitted from Inner Classes That Don't Use Them

    XMLWordPrintable

Details

    • Sub-task
    • Resolution: Delivered
    • P3
    • 18
    • 18
    • tools
    • Verified

    Description

      Prior to JDK 18, when javac compiles an inner class it always generates a private synthetic field with a name starting with `this$` to hold a reference to the enclosing instance, even if the inner class does not reference its enclosing instance and the field is unused.

      Starting in JDK 18, unused `this$` fields are omitted; the field is only generated for inner classes that reference their enclosing instance.

      For example, consider the following program:

      ```
      class T {
          class I {
          }
      }
      ```

      Prior to JDK 18, the program would be translated as:

      ```
      class T {
          class I {
              private synthetic T this$0;
              I(T this$0) {
                  this.this$0 = this$0;
              }
          }
      }
      ```

      Starting in JDK 18, the unused `this$0` field is omitted:

      ```
      class T {
          class I {
              I(T this$0) {}
          }
      }
      ```

      Note that the form of the inner class constructor is not affected by this change.

      The change may cause enclosing instances to be garbage collected sooner, if previously they were only reachable from a reference in an inner class. This is typically desirable, since it avoids a source of potential memory leaks when creating inner classes that are intended to outlive their enclosing instance.

      Subclasses of `java.io.Serializable` are not affected by this change.

      Attachments

        Activity

          People

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

            Dates

              Created:
              Updated:
              Resolved: