Java尝试使用资源 - 关闭资源的顺序

时间:2018-03-27 05:35:52

标签: java try-with-resources

运行以下代码

class MyResource1 implements AutoCloseable {
    public void close() throws IOException {
        System.out.print("1 ");
    }
}

class MyResource2 implements Closeable {
    public void close() throws IOException {
        throw new IOException();
    }
}

public class MapAndFlatMap {
    public static void main(String[] args) {
        try (
                MyResource1 r1 = new MyResource1();
                MyResource2 r2 = new MyResource2();
            ) {
            System.out.print("T ");
        } catch (IOException ioe) {
            System.out.print("IOE ");
        } finally {
            System.out.print("F ");
        }
    }
}

我得到以下输出

T IOE 1 F 

但我期待

T 1 IOE F

即使在改变资源顺序之后,尝试如下

MyResource2 r2 = new MyResource2();
    MyResource1 r1 = new MyResource1();

输出没有变化。据我所知,资源将在其声明的相反方向关闭。这是对的吗?

1 个答案:

答案 0 :(得分:4)

这是一种记录在案的行为:" close methods of resources are called in the opposite order of their creation"