Try-With-Resource Enhancements in Java 9
Final and effectively final variables can be placed in try-with-resource blocks, starting in Java 9. That will give you more options for automatic resource management.
Join the DZone community and get the full member experience.
Join For FreeTry-with-resources was a great feature introduced in Java 7 to automatically manage resources using an AutoCloseable
interface. This helps a lot, of course, as we have no need to close the resources explicitly in our code.
Java 7 Code
public void loadDataFromDB() throws SQLException {
Connection dbCon = DriverManager.getConnection("url", "user", "password");
try (ResultSet rs = dbCon.createStatement().executeQuery("select * from emp")) {
while (rs.next()) {
System.out.println("In loadDataFromDB() =====>>>>>>>>>>>> " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println("Exception occurs while reading the data from DB ->" + e.getMessage());
} finally {
if (null != dbCon)
dbCon.close();
}
}
In the above example, we defined the Connection object outside the try-with-resource block, hence we need to close it explicitly in the finally block. We can't put a dbCon object reference in our try-with-resource block, which was an obvious bug in Java 7. Fortunately, it was fixed in Java 9.
Java 9's Solution
Java 9 will give us this feature, available in the java.base
module, so the above code could be rewritten as below:
public void loadDataFromDB() throws SQLException {
Connection dbCon = DriverManager.getConnection("url", "user", "password");
try (dbCon; ResultSet rs = dbCon.createStatement().executeQuery("select * from emp")) {
while (rs.next()) {
System.out.println("In loadDataFromDB() =====>>>>>>>>>>>> " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println("Exception occurs while reading the data from DB ->" + e.getMessage());
}
}
You can see that the object reference dbCon has been kept inside the try-with-resource block, so any resource as a final or effectively final variable can be placed in try-with-resource blocks and would be eligible for automatic resource management.
Enjoy the enhanced features of ARM!
Opinions expressed by DZone contributors are their own.
Comments