Aliuk
Aliuk

Reputation: 1359

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.

Upvotes: 11

Views: 3735

Answers (2)

Aliuk
Aliuk

Reputation: 1359

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);) {
    ...
}

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140319

The ordering is the same: it's always the reverse of the order in which resources are specified. From JLS:

Resources are closed in the reverse order from that in which they were initialized.

However, if the later-specified resources themselves invoke the close() method of the earlier-specified resources (as is the case with BufferedReader and ObjectOutputStream), it may look like they are not happening in the expected order (and that close() will be invoked multiple times).

Upvotes: 14

Related Questions