javafinaltry-with-resourceseffectively-final

why resources declared outside the try-with-resources statement need to be final or effectively final in java?


why resources declared outside the try-with-resources statement need to be final or effectively final in java? ex: why object_name in the below code needs to be final or effectively final?

type object_name = new type();
try (object_name) {
  ...
}

Solution

  • It's just a knee jerk default (a good one): When in doubt and there is no particularly good reason to allow some weird usage that doesn't appear to make much sense, just.. don't allow it. If it turns out that a lot is lost by not allowing it, you can simply allow it later. You can't do the reverse - disallowing it later would be backwards incompatible.

    The specific reasoning here is most likely this simple concept:

    What is the thing you are 'try-with'ing here? Is it [A] the variable, or [B] the object? Imagine this code:

    class DummyClosable implements AutoClosable {
      String print;
    
      DummyClosable(String print) {
        this.print = print;
      }
    
      @Override public void close() {
        System.out.println(print);
      }
    }
    
    class Example {
      public static void main(String[] args) {
        DummyClosable dc = new DummyClosable("a");
        try (dc) {
          dc = new DummyClosable("b");
        }
      }
    }
    

    Does that print 'a', or 'b'? I can see how someone is utterly convinced it should print 'a', and I can see how someone is utterly convinced it should print 'b'.

    But I can especially see how the vast majority of java programmers will quickly figure out it will print one or the other, but aren't sure which one it is. Because trying to auto-close non-finals is extremely rare, they won't have the experience and thus will mostly just curse the code: They now need to either guess what it does, or try to figure it out from context with the rather drastic penalty that this perpetuates any bugs in what this does, or experiment/read docs which takes time.