Search code examples
javajdbcjava-iotry-with-resourcesautocloseable

Try-with-resources close order


I am looking at examples of try-with-resources in Java and I understand the following one:

try (Connection conn = DriverManager.getConnection(url, user, pwd);
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(query);) {
  ...
}

So, the order of closing is:

rs.close();
stmt.close();
conn.close();

which is perfect because a connection has a statement and a statement has a result set.

However, in the following examples, the order of close I think it is the reverse of the expected:

Example 1:

try (FileReader fr = new FileReader(file);
     BufferedReader br = new BufferedReader(fr)) {
  ...
}

The order of closing is:

br.close();
fr.close();

Example 2:

try (FileOutputStream fos = new FileOutputStream("testSer.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fs);) {
    ...
}

The order of closing is:

oos.close();
fos.close();

Are these examples correct? I think the close in those examples should be different because:

  1. In the example 1 a BufferedReader has a FileReader.
  2. In the example 2 an ObjectOutputStream has a FileOutputStream.

Solution

  • I think I wasn't right when I said "a connection has a statement and a statement has a result set". Maybe it's the opposite "a result set has a statement and a statement has a connection" or at least "a result set was created by a statement and a statement was created by a connection".

    So I think:

    try (Parent parent = new Parent();
         Child child = parent.createChild();) {
        ...
    }
    

    Is equivalent to:

    try (Parent parent = new Parent();
         Child child = new Child(parent);) {
        ...
    }