Keep API design in mind.

The try-with-resources statement introduced in Java 7 allows us to adopt an approach where certain objects could be opened, being visible in the try block, and immediately closed when the execution reaches the end of that scope. This was a huge improvement for managing scarce resources, in comparison with the old approach of overriding the finalize() method (which we never exactly know when will be executed.)

Over the years, I was repeatedly seeing the following approach on some applications, which motivated me to write this post. Consider this code snippet for executing an SQL statement using JDBC:

Java

1

import javax.sql.DataSource;

2

import java.sql.*;

3

...

4

  public BigDecimal getSum(long empId) throws SQLException {

5

    String sql = "select sum(salary) from payroll where empId=?";

6

    try(PreparedStatement stmt = myDataSource.getConnection().prepareStatement(sql)) {

7

      stmt.setLong(1, empId);

8

      try(ResultSet rs = stmt.executeQuery()) {

9

        if (rs.next())

10

          return rs.getBigDecimal(1);

11

        return BigDecimal.ZERO;

12

      }

13

    }

14

  }

15

...

What the code does is unimportant, but the connection handling is very important. The outer try-with-resources ensures that at the end of its block, the PreparedStatement will be closed. The same thing goes with the ResultSet in the inner try-with-resources.

Here is the catch: the Connection object returned from the DataSource will never be closed. Since it was not bound to any variable inside the try-with-resources, according to the JLS (see References), the resource in the outer try-with-resources is of type PreparedStatement. As a result, the Connection instance is not participating in the statement, and so its close() method is never called.

The solution is easy: declare a variable referencing the resource you want to be auto-closed.

#java #java resources #multiple autocloseable instances #avoid method chaining #using multiple autocloseable instances

Avoid Method Chaining When Using Multiple AutoCloseable Instances
1.25 GEEK