Example & Tutorial understanding programming in easy ways.

Describe the feature of try-with-resorce feature of jdk 1.7?

One of the Java 7 features is try-with-resources statement for automatic resource management. A resource is an object that must be closed once your program is done using that perticular resources, like a File resource or JDBC resource for database connection or a Socket connection resource.

Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement.

This approach used to cause memory leaks and performance hit when we forgot to close the resource. It is an important and required change in the java to enhance the security of the java application.

Hare is the template used before java 7.

try{
    //open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
    // Exception handling like FileNotFoundException, IOException etc
}finally{
    // close resources
}

The template used in java 7.

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
    // exception handling
}
// resources are closed as soon as try-catch block is executed.

Now lets see some examples how differently the resources get managed in java before and after the jdk1.7

Java 6 resource management example:-


package r4rjdk7;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class Java6ResourceManagement {

public static void main(String[] args) {

   BufferedReader br = null;

   try {

    br = new BufferedReader(new FileReader("D:\r4r.txt"));

    System.out.println(br.readLine());

        } catch (IOException e) {

                e.printStackTrace();

         } finally {

        try {

            if (br != null)

                  br.close();

                 } catch (IOException ex) {

              ex.printStackTrace();

          }

     }

  }

}

Java 7 resource management example:-

package r4rjdk7;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class Java7ResourceManagement {

public static void main(String[] args) {

          try (BufferedReader br = new BufferedReader(new FileReader(

            "C:\r4r.txt"))) {

                      System.out.println(br.readLine());

                      } catch (IOException e) {

                          e.printStackTrace();

                     }

              }

      }


Benefits of using try with resources

  •     More readable code and easy to write.
  •     Automatic resource management.
  •     Number of lines of code is reduced.
  •     No need of finally block just to close the resources.
  •     We can open multiple resources in try-with-resources statement separated by a semicolon.

Read More →