Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it mandatory to put inner try-with-resources or everything inside one of the try-with-resources will be autoclosed?

Is it mandatory to put inner try-with-resources or everything inside one of the try-with-resources will be autoclosed?

    try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(dsProperties)) {

        // still necessary for Connection to close if inside
        // try-with-resources?
        try (Connection conn = ds.getConnection()) {

            String sql = "SELECT * FROM users";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {

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

                    while (rs.next()) {
                        System.out.println(rs.getString("email"));
                        System.out.println(rs.getString("password"));
                    }

                }
            }

        }

    } catch (SQLException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    }
like image 505
DevDio Avatar asked Feb 04 '17 13:02

DevDio


1 Answers

In a try-with-resources block, only the resources in the try statement will be closed automatically by the try-with-resources construct. Other resources within the block are unrelated, and must be managed(*).

However, you can put multiple resources in the try statement, instead of using multiple try-with-resources (one for each resource) for example:

try (PreparedStatement stmt = conn.prepareStatement(sql);
     ResultSet rs = stmt.executeQuery()) {
    while (rs.next()) {
        System.out.println(rs.getString("email"));
        System.out.println(rs.getString("password"));
    }
}

(*)As @alexander-farber pointed out in a comment, there are also some resources that get closed automatically by other mechanism, for example a ResultSet gets closed when the Statement that generated it gets closed. Although you don't manage those resources explicitly, they are managed by their implementation.

like image 166
janos Avatar answered Sep 20 '22 18:09

janos