Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 383
Aliuk Avatar asked Oct 08 '18 09:10

Aliuk


People also ask

What is the order of closure of the resources from try with resources?

The order of closing is: oos. close(); fos. close();

Does try with resources close before finally?

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Does try with resources automatically close?

The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.

Can you explain about try with resources?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.


1 Answers

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).

like image 126
Andy Turner Avatar answered Sep 29 '22 08:09

Andy Turner