Java Essential Tips: Automatic Resource Management

Java7 introduced many features that simplifies coding which are overhead in older Java versions. In this blog we will see the feature called Automatic Resource Management.
This is really a good feature in Java7 which close the resources like IO streams automatically. Everything you need to do is implement java.lang.AutoCloseable.

try-with-resources Statement

try-with-resources statement simply has the instantiation of any AutoClosable type in try statement with or without catch/finally block and it will be closed regardless of whether the try statement completes normally or abruptly. For example check the following code:
public String readMyFile(String path) throws IOException{
try(BufferReader reader=new BufferedReader(new FileReader(path)){
return reader.readLine()
}
}

The java.io.BufferedReader in Java 7 or later, implements the interface java.lang.AutoCloseable so that it will be automatically closed once the execution is done.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Permanent link to this article: https://blog.openshell.in/2013/08/java-essential-tips-automatic-resource-management/

Leave a Reply

Your email address will not be published.