Try with resource enhancements in Java 9

Reading Time: 2 minutes

We all have done I/O operations in our code which used to be very troublesome when it comes to always keep in mind closing the resources once the usage has been made. But, when in Java 7, Try-With-Resource was introduced, this limitation was taken care of. Now a user needs not to worry about the open resources.
To understand what enhancements have been done in Java 9 for Try-With-Resource,  let us understand what is it first.

 Try-With-Resource:

The Try-with-resource statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement 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.
Let’s look at this example:

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
public class TryWithResourceExample {  
    public static void main(String[] args) throws FileNotFoundException {  
        try(FileOutputStream file = new FileOutputStream("test_try_with_resources.txt");){ 
             String fileData = "Let us write to an output file"; 
             byte bytes[] = fileData.getBytes();       
             file.write(bytes);      
             System.out.println("Written the data to the file");           
        }catch(Exception ex) {  
            System.out.println(ex);  
        }         
    }  
}

In this example, the resource declared in the try-with-resources statement is a FileOutputStream. The declaration statement appears within parentheses immediately after the try keyword. The class FileOutputStream, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the FileOutputStream instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly. Prior to this, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly

Problem with the Try-With-Resources in Java 7:

 FileOutputStream file = new FileOutputStream("test_try_with_resources.txt");
       try(file){
       // I/O operation code goes here
       }

This code will give you a compile-time exception because the resource is declared outside the scope of the Try-With-Resource statement.

The workaround goes by keeping the duplicate to the resource reference like this:

FileOutputStream file = new FileOutputStream("test_try_with_resources.txt"); 
      try(FileOutputStream fileStream = file){
      // I/O operation code goes here
      }

We created another reference to the already declared output stream within the scope of Try-With-Resource.

Java 9 – Try-With-Resources Enhancements:

Java 9 provided a major enhancement to the traditional Try-With-Resource statement. It allows us to declare the resource outside of the Try-With-Resource block.  If we have a resource that is already declared outside the Try-With-Resource Statement as final or effectively final, then we do not need to declare a local variable. We can use the previously created variable within Try-With-Resource Statement without any issues as shown below:

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
public class TryWithResourceExample {  
    public static void main(String[] args) throws FileNotFoundException { 
       FileOutputStream file = new FileOutputStream("test_try_with_resources.txt");
       try(file){ 
            String fileData = "Let us write to an output file";
            byte bytes[] = fileData.getBytes();       
            file.write(bytes);      
            System.out.println("Written the data to the file");           
        }catch(Exception ex) {  
            System.out.println(ex);  
        }         
    }  
}

So this is how Java 9 made try with resources simple by allowing effectively final variables to be used as resources in it.

I hope, you have liked my blog. If you have any doubts or suggestions to make please drop a comment. Thanks!

References:
Oracle documentation

Knoldus-Scala-Spark-Services

Written by 

Vinisha Sharma is a software consultant having more than 6 months of experience. She thrives in a fast pace environment and loves exploring new technologies. She has experience with the languages such as C, C++, Java, Scala and is currently working on Java 8. Her hobbies include sketching and dancing. She believes Optimism and a learning attitude is the key to achieve success in your life