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

Illegal writes to final fields are allowed from lambdas inside a constructor

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Duplicate
    • Icon: P3 P3
    • None
    • 8u131, 9
    • tools
    • None

      public class UpdateFinalField {
          final int f;
          final Runnable updater;

          UpdateFinalField() {
              updater = () -> { f = 1; };
              f = 0;
          }

          public static void main(String[] args) {
              UpdateFinalField u = new UpdateFinalField();
              System.out.println("u.f = " + u.f);
              u.updater.run();
              System.out.println("u.f = " + u.f);
          }
      }

      $ jdk.8u131/bin/javac -d classes.8 UpdateFinalField

      $ jdk.8u131/bin/java -cp classes.8 UpdateFinalField
      u.f = 0
      u.f = 1

      $ jdk.9/bin/java -cp classes.8 UpdateFinalField
      u.f = 0
      u.f = 1

      $ jdk.9/bin/javac -d classes.9 UpdateFinalField

      $ jdk.9/bin/java -cp classes.9 UpdateFinalField
      u.f = 0
      Exception in thread "main" java.lang.IllegalAccessError: Update to non-static final field UpdateFinalField.f attempted from a different method (lambda$new$0) than the initializer method <init>
      at UpdateFinalField.lambda$new$0(UpdateFinalField.java:6)
      at UpdateFinalField.main(UpdateFinalField.java:13)

            dlsmith Dan Smith
            vlivanov Vladimir Ivanov
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: