Nov 6, 2012

Java 7 Overview: Automatic Resource Management

Java 7 support Automatic Resources Management through the try-with-resources statement. A resource is an object that must be closed after the program is finished with it. The try statement could declare one or more resources, where it ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource in this regard.

The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

The following readAndWriteData example use try-with-resources statement containing two declarations that are separated by a semicolon.
public void readAndWriteData(File src, File dest)
{
  try (InputStream in = new FileInputStream(src),
     OutputStream out = new FileOutputStream(dest))
  {
      byte[] buf = new byte[1024];
      int n;
      while (n = in.read(buf)) >= 0)
        out.write(buf, 0, n);
  }
}
In this example, the resource declared in the try-with-resources statement is InputStream and OutputSream. The declaration statement appears within parentheses immediately after the try keyword. InputStream and OutputSream classes, in Java SE 7 and later, both implements java.lang.AutoCloseable interface. Because the InputStream/OutputSream instances are declared in a try-with-resource statement, they will be closed regardless of whether the try statement completes normally or abruptly. 

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.

The following example uses a finally block instead of a try-with-resources statement. 
public void readAndWriteData(File src, File dest)
{
  InputStream in = null;
  OutputStream out = null;
  try{
      in = new FileInputStream(src);
      out = new FileOutputStream(dest);
      byte[] buf = new byte[1024];
      int n;
      while (n = in.read(buf)) >= 0){
         out.write(buf, 0, n);
      }
   }catch(IOEception e){
        e.printStackTrace();
   }finally{
           try{
               if(in != null){
                 in.close();
               }
               if(out != null){
                 out.close();
               }
           }catch(IOException e){
                e.printStackTrace();
          }
   }
}
Related Posts

Java 7 Overview: String in Switch Support

Java 7 Overview: Multi-Catch Support

No comments:

Post a Comment