Learnitweb

Java – Try with Resources

1. Introduction

ARM (Automatic Resource Management) using try-with-resources was added in Java 7. This is one of the small language changes added to JDK 7 as part of Project Coin. This feature makes it easier to work with external resources like files, printers, devices. A resource is an object that needs to be closed or disposed after successful completion of code or in case of any error.

The try-with-resources statement is a try statement that declares one or more resources.

Following is an example to read file without try-with-resources:

package test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {
     private static final String FILENAME = "E:\\testFile.txt";
     public static void main(String[] args) {
          BufferedReader bufferedReader = null;
          FileReader fileReader = null;
          String strCurrentLine;
          try {
               fileReader = new FileReader(FILENAME);
               bufferedReader = new BufferedReader(fileReader);
               while ((strCurrentLine = bufferedReader.readLine()) != null) {
                    System.out.println(strCurrentLine);
               }
          } catch (IOException e) {
               e.printStackTrace();
          } finally {
               try {
                    if (bufferedReader != null)
                         bufferedReader.close();
                    if (fileReader != null)
                         fileReader.close();
               } catch (IOException ex) {
                    ex.printStackTrace();
               }
          }
     }
}

If you look at above code you will find that lot of code is there in finally block just to close the resources. Before closing the resource, we need to check for null condition. If we try to read a file which does not exist, we’ll have an exception. In such case, we need to take care of closing of resources as well. Thus, a lot needed to be done for handling resources.

Problems with the above approach are:

  • Programmer has to write code to close all opened resources. This increases the complexity of the code and readability of the code.
  • Programmer has to write explicit finally blocks which increases the length of code.

To overcome these problems Sun People introduced “try with resources” in 1.7 version. This can be handled properly with the help of ARM.

2. try-with-resources

The program written previously in this tutorial can be re-written with the help of try-with-resources as follows:

package test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {
     private static final String FILENAME = "E:\\testFile.txt";
     public static void main(String[] args) {
          String strCurrentLine;
          try (FileReader fileReader = new FileReader(FILENAME);
               BufferedReader bufferedReader = new BufferedReader(fileReader)){
               while ((strCurrentLine = bufferedReader.readLine()) != null) {
                    System.out.println(strCurrentLine);
               }
          } catch (IOException e) {
               e.printStackTrace();
          } 
      }
}

The main advantage of try-with-resources is that the resources opened as part of try block will be closed automatically once the control reaches the end of the try block either normally or abnormally. Hence you are not required to close the resources explicitly. This reduces the length of the code and complexity.

3. Important points about try-with-resources

  • Syntax for try-with-resources is as follows:
    try(resource1; resource2) {}
  • You can declare any number of resources separated with semicolon (;).
  • Semi colon is not allowed after last resource. 
  • Resource must implement java.lang.AutoCloseable. The AutoCloseable interface introduced in Java 1.7 and contains only one method close.
  • It is possible with try-with-resources to have no catch or finally. The try-with-resources statement logically calls finally block to close resources.
  • You can also have your own catch and finally block with try-with-resources.
  • ARM automatically cleans up resources before calling catch and finally block. That is, close method of resources is called before catch and finally block.
  • The resources are cleaned up in reverse order of the declaration. That is, resource2 is cleaned before resource1. This is done to support the fact that resource2 can be dependent on resource1.
  • All resource reference variables should be final or effectively final. You can’t perform reassignment within the try block.

3. Conclusion

In this tutorial, we discussed how to use try-with-resources, its advantages and how to replace trycatch, and finally with try-with-resources.