javatry-with-resourcesautocloseable

Using "try with resources" for resources created without any reference


Consider the following situation :

try (ResultSet resultSet = DriverManager.getConnection("jdbc:...", "user", "pass")
                                      .createStatement().executeQuery(sql)) {    
                    .
                    .
                    .
}

This is a situation where three resources have been created inside try resources: a Connection, a Statement, and a ResultSet.

What will happen to these three resources after the try block ends? Will they all be closed, even if they haven't any reference to them, or will only the resultSet be closed?

Is this safe to declare AutoCloseable resources without any reference to them in try with resource blocks?


Solution

  • Only the ResultSet will be closed. If you want multiple resources to be closed, you need to declare them separately:

    try (Connection conn  = DriverManager.getConnection("jdbc:...", "user", "pass");
         Statement stmt = conn.createStatement();
         ResultSet resultSet = stmt.executeQuery(sql)) {    
    
         // do stuff...
    }