Tuesday, December 30, 2014

JDK 7 : try-with-resources

The try-with-resources Statement

There is a big full stop for the resource leak in JAVA.
Instead of breaking our heads to properly releasing used resources after its usage,
from JAVA SE 7 onwards we just need to focus only on business using those resources.
Past couple of decades, we followed as best practice in releasing the resource using the finally block.

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();

Many of the close() function implementation will close themself, and makes a no mark in system.
However, few times it may do additional task 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 instanciated in try statement. Those resources automatically get closed after try block executions.
For the resource implementor, its recommended not to throw any exception while doing close() call.
And align the resource close operation such that it is closing itself.

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


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