Java 7 try with resources (autocolosable) implementation

My question is more about the type than how

I know that there are the following jobs in Java 7:

try (
            FileInputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(target);
    ) {
        .....................
      } catch (......) {
       ...............
      }

The following is a syntax error:

FileInputStream in;
    FileOutputStream out;
    try (
            in = new FileInputStream(source);
            out = new FileOutputStream(target);
    ) {
        .....................
      } catch (......) {
       ...............
      }

I wonder why the closable / autoclosable reference is so important for the try block to be local? If we don't own it instead of closing it, is it just logic?

Solution

I don't have a reference for this language design decision, but I think the problem is that it would be dangerous to allow automatic closure of nonlocal variables - that is, it would allow many unsafe coding styles Start with the Java language specification:

If resources are not final, they may be reallocated in the try block, resulting in resource leakage Since they are final (implicit or explicit), the compiler must do a lot of extra work to ensure that the variable is definitively unassigned when entering the try resource specification It may also need to change the compiler semantics of final, because the variable should not have a valid value after the try block exits; Of course, they are not the values assigned to them in the try resource specification The cleanest (and perhaps only) thing to do is to make the variable out of range when the try block exits

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>