Many a times we forget to the close the file/jdbc resources that we open inside a try block after the operations are complete. This can cause memory leak issue.
Starting from JDK 1.7, a new feature try-with-resource was introduced.This feature allows user to declare one or more resources in the try block. The try-with-resources will close the resource at the end of the try block.
Syntax for try-with-resources :
1 2 3 |
try(open resource here){ //... Perform opertaion on the opened resource } |
Prior to JDK 1.7 we used to close the resources in the finally block
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
BufferedReader br = null; try { br = new BufferedReader(new FileReader("C:\\kscodesDemo.txt")); // ----- //Operations on br } catch (IOException ioe) { System.err.println(ioe); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } |
Using the try-with-resources in JDk 1.7
1 2 3 4 5 6 7 8 9 10 11 |
try (BufferedReader br = new BufferedReader(new FileReader("C:\\kscodesDemo.txt"))) { // ----- // Operations on br //Once operations are performed "br" is automatically closed here. } catch (IOException e) { e.printStackTrace(); } |
Please Note:
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.See the Javadoc of the AutoCloseable
and Closeable
interfaces for a list of classes that implement either of these interfaces
Use of try-with-resources in JDBC statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
String query = "SELECT name,salary FROM employee"; Connection con = //get connection object; try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String name = rs.getString("name"); float salary = rs.getFloat("salary"); System.out.println("Name ::" + name + ", " + "Salary :: " + salary); } } catch (SQLException e) { System.err.println(e); } |