Java 7 Try-With-Resources (AutoCloseable) 实现

标签 java stream try-catch java-7

我的问题更多的是为什么而不是如何

我知道在 Java 7 中可以执行以下操作:

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

下面给出语法错误:

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

我很好奇为什么 Closable/Autoclosable 引用对 try 来说是local 如此重要> 阻止? 如果我们不拥有它,关闭它会很危险,这只是逻辑吗?

最佳答案

我没有此语言设计决策的引用,但我认为问题在于允许自动关闭非局部变量是危险的——也就是说,它会允许许多不安全的编码风格。来自 the Java Language Specification :

A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final.

如果资源不是final,那么在try block 中它们可能会被重新分配,从而导致资源泄漏。因为它们是(隐式或显式)final,编译器必须做很多额外的工作来确保变量是 definitely unassigned。在输入 try 资源规范时。它可能还需要更改 final 的编译器语义,因为在 try block 退出后,变量实际上不应该具有有效值;当然不是 try 资源规范中分配给它们的值。最干净(也许唯一)的做法是在 try block 退出时让变量超出范围。

关于Java 7 Try-With-Resources (AutoCloseable) 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139051/

相关文章:

java - 用于本地测试的 Redshift

java - Hybris SOLR - 使用自由范围 slider 的 Facet 价格值

flutter - 如何在 Flutter 中使用 Riverpod 关闭 StreamProvider

c# - C# 错误处理练习中的 throw 关键字负责什么

java - 当 try block 中的多行抛出异常时,使用 Try-With-Resources 而不是 finally block

Java:如何编写 try-catch-repeat block ?

java - Spring boot RestTemplate 发布 400 错误

java - 历史记录队列不释放第一个文件

c# - 我如何在 t4 预处理模板中使用流而不是 stringbuilder

node.js - 在pdf中写入字节