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

Creating a VarHandle for a static field triggers class initialization

XMLWordPrintable

    • b07
    • generic
    • generic

      The specification (= JavaDoc) of MethodHandles.Lookup#findStaticVarHandle and MethodHandles.Lookup#unreflectVarHandle state

      ```
      If the returned VarHandle is operated on, the declaring class will be
      initialized, if it has not already been initialized.
      ```
      (from https://github.com/openjdk/jdk/blob/160944bc6bd94d2927f398cf7732027c1b836a42/src/java.base/share/classes/java/lang/invoke/MethodHandles.java#L3194)

      I interpret "is operated on" as "creating the VarHandle itself does not trigger class initialization, only the first usage of the VarHandle will initialize the class".

      But class initialization is always triggered already when the VarHandle for a static field is created. This is fairly obvious from the JDK code: https://github.com/openjdk/jdk/blob/160944bc6bd94d2927f398cf7732027c1b836a42/src/java.base/share/classes/java/lang/invoke/VarHandles.java#L115

      So the current implementation is not in sync with the specification, either one of them need to be fixed.

            liach Chen Liang
            cwimmer Christian Wimmer (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: