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