Is it mandatory to use try-with-resources internal resources or will everything inside one of the try-in-resources be closed automatically?

Is it mandatory to use internal try-with-resources or will everything inside one of the try-in-resources be closed automatically?

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(); } 
+5
source share
1 answer

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

However, you can put multiple resources in a try , 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 noted in a comment by @ alexander-farber , there are also some resources that are automatically closed by another mechanism, for example, a ResultSet closed when the Statement that generated it is closed. Although you do not use these resources explicitly, they are controlled by their implementation.

+4
source

Source: https://habr.com/ru/post/1263819/


All Articles