Friday, April 19, 2019

Java 9 - Try with resources Improvement


Java 9  -  Try with resources Improvement



In this blog, I’ll discuss about try with resources which was introduced with JDK 7 and what enhancement has been done in JDK 9.

Try with resources is a great feature which was introduced in JDK 7 that helps in closing resources automatically after being used.

Any class can be used as resources if that class implements AutoClosable Interface.

Advantages
  • As try with resources closes all the resources file Automatically which prevents memory leaks.
  • More readable code as you don’t have to write unnecessary code. 

Let’s understand it with an example

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * This class will explain the try with resources which was introduced with
 * JDK7.
 *
 * @author AbdulWaheed18@gmail.com
 *
 */
public class ExmapleWithJava7 {

       public static void main(String[] args) throws FileNotFoundException {

             try (FileOutputStream fileStream = new FileOutputStream("App.log");) {
                    String logMessage = "[INFO] DATA NEED TO BE WRITTEN";
                    byte logMessageInBytes[] = logMessage.getBytes();
                    fileStream.write(logMessageInBytes);
                    System.out.println("Updated log files.");
             } catch (Exception e) {
                    // handle error
             }
       }
}

With JDK7, we have to declared all resources within try block but which is not possible for every resource like DB connection. To use DB connection, we have to close the resources explicitly in finally block which was an obvious bug.

With the JDK 9 enhancement, you can just pass the reference in try block without declaring within try block.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * This class will explain enhancement of try with resources block which was
 * introduced with JDK9 .
 *
 * @author AbdulWaheed18@gmail.com
 *
 */
public class ExmapleUsingJava9 {

       public static void main(String[] args) throws FileNotFoundException {
             FileOutputStream fileStream = new FileOutputStream("App.log");
             try (fileStream) {
                    String logMessage = "[INFO] DATA NEED TO BE WRITTEN";
                    byte logMessageInBytes[] = logMessage.getBytes();
                    fileStream.write(logMessageInBytes);
                    System.out.println("Updated log files.");
             } catch (Exception e) {
                    // handle error
             }
       }
}

You can download the Source code from here.

Happy Coding…!!!





No comments:

Post a Comment

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...