Tuesday, December 30, 2014

JDK 7 : try-with-resources

There is a big full stop for the resource leak in Java.
Instead of breaking our heads trying to properly release used resources after their usage, from Java SE 7 onwards we just need to focus only on the business using those resources. For the past couple of decades, we followed the best practice of releasing the resource using the finally block.
 
java
FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(new FileReader("text.txt"));
try {
   System.out.println(br.readLine());
} finally {
 if (br != null) br.close();
 if (fr != null) fr.close();
}
Use code with caution.
Many of the close() function implementations will close themselves, and leave no mark in the system.
However, few times it may do additional tasks to release its parent also. For instance, ResultSet.close() implementations. 
From JDK 7 onwards, any resource object which extends either java.lang.AutoCloseable or java.lang.Closeable can be instantiated in a try statement. Those resources automatically get closed after the try block execution.
For the resource implementor, it's recommended not to throw any exception while calling close().
And align the resource close operation such that it is closing itself
. 
java
try (FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr)) {
System.out.println(br.readLine());
}

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com