Exploring Java 7 : Try-with-resources

Try-with-Resource is new featured added in Java 7. Personally, I like this feature very much, as it helps to reduce a lot of boiler plate code.

Consider a scenario, where we have to release a system resource, like JDBC Connection or File Stream. Prior to Java 7, it meant that developer has to write a lot of boiler plate code to release that resource. In order to ensure releasing of resource in all the situations, one has to use finally block as well for exception cases. Consider following example, written with Java 6:

String readFirstLine(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null)
    br.close();
  }
 }
Clearly, one has to write almost 4-5 lines for closing each resource. Now, what Java 7 did is that it made the process of closing resource automatic.

In Java 7, a resource is defined as "An object of type java.lang.AutoCloseable.". This AutoCloseable interface has a single method close() and this method is invoked automatically when a resource is used with try block. See below example:
String readFirst(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();
  }
 }

Impressive!!! Isn't it? We have reduced boiler plate code drastically and there is no scope of accidentally forgetting to close a resource. All resource will be freed automatically.

Few points to remember:
  • A resource must be declared in parenthesis, immediately after try block.
  • A Try-with-Resource can have catch and finally blocks, just as with try block.
  • There can be multiple resources in a single Try-with-Resource block
  • public void readEmployees(Connection con){
      String sql = "Select * from Employee";
      try (Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql)){
       //Work with Statement and ResultSet   
      } catch (SQLException sqe) {
       sqe.printStackTrace();
      }
     }
  • In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration

4 comments:

Anonymous said...

Good stuff. Another worth noting feature from Java 7 which I like is fork join framework, which allows you to take full advantages of multiple cores in your server.

Vineet Mangal said...

Yeah!!

Unknown said...

Great tutorial but you should have mentioned the only difference between normal try-catch and try-with-resources. I have written a blog post to explain this.

http://www.journaldev.com/592/try-with-resource-example-java-7-feature-for-automatic-resource-management

Please have a look.

Java Discover said...

Hi,
You can few other Java 7 working sample code - http://www.javadiscover.blogspot.com/search/label/Java%207

Thanks
Anand