Automatic Resource Management in Java | try with resource statements

Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources.
This statement ensures that each resource is closed at the end of the statement which eases working with external resources that need to be disposed or closed in case of errors or successful completion of a code block.

What is a resource?
A resource is an object that must be closed after the program is finished using it. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Old method of resource cleanup – Using finally

In earlier versions of Java before JDK 1.7, the closing of resources was done using the finally block.

// Java program to illustrate cleaning of

// resources before Java 7

importjava.io.*;

importjava.util.*;

importjava.io.*;

classResource

{

publicstaticvoidmain(String args[])

{

BufferedReader br = null;

String str = " ";

System.out.println("Enter the file path");

br = newBufferedReader(newInputStreamReader(System.in));

try

{

str = br.readLine();

}

catch(IOException e)

{

e.printStackTrace();

}

try

{

String s;

// file resource

br = newBufferedReader(newFileReader(str));

while((s = br.readLine()) != null)

{

//print all the lines in the text file

System.out.println(s);

}

}

catch(IOException e)

{

e.printStackTrace();

}

finally

{

try

{

if(br != null)

//closing the resource in 'finally' block

br.close();

}

catch(IOException ex)

{

ex.printStackTrace();

}

}

}

}

Output:

hello
java

The new way – Using try-with-resources

In try-with-resources method there is no use of finally block. the file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements AutoCloseable interface and those object should also be local. The resource will be closed automatically regardless of whether try statement completes normally or abruptly.Syntax:
The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

Multiple resources can be used inside a try-with-resources block and have them all automatically closed. In this case, the resources will be closed in the reverse order in which they were created inside the brackets.

// Java program to illustrate

// Automatic Resource Management

// in Java with multiple resource

classResource

{

publicstaticvoidmain(String s[])

{

//note the order of opening the resources

try(Demo d = newDemo(); Demo1 d1 = newDemo1())

{

intx = 10/0;

d.show();

d1.show1();

}

catch(ArithmeticException e)

{

System.out.println(e);

}

}

}

// custom resource 1

classDemo implementsAutoCloseable

{

voidshow()

{

System.out.println("inside show");

}

publicvoidclose()

{

System.out.println("close from demo");

}

}

//custom resource 2

classDemo1 implementsAutoCloseable

{

voidshow1()

{

System.out.println("inside show1");

}

publicvoidclose()

{

System.out.println("close from demo1");

}

}

Output:

close from demo1
close from demo

NOTE: In the above example, Demo and Demo1 are the custom resources managed inside the try block. Such resources need to implement the AutoCloseable interface. When we open any such AutoCloseable resource in special try-with-resource block, immediately after finishing the try block, JVM calls this.close() method on all resources initialized in try block.Important Points:

finally blocks were used to cleanup the resources before Java 7.

After java 7, resource cleanup is done automatically.

ARM is done when you initialize resource in try-with-resources block because of the interface AutoCloseable. Its close method is invoked by JVM as soon as try block finishes.

Calling close() method might lead to unexpected results.

Resource that we use in try-with-resource must be subtypes of AutoCloseable to avoid compile time error.

The resources which are used in multiple resource ARM must be closed in reverse order as given in above example

This article is contributed by Apoorva singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.