Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Automatic Resource Management in Java ( try with resource statements )
Next article icon

Automatic Resource Management in Java ( try with resource statements )

Last Updated : 08 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 of or closed in case of errors or successful completion of a code block.

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.

An 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
// Java program to illustrate cleaning of // resources before Java 7  import java.io.*; import java.util.*; import java.io.*; class Resource {     public static void main(String args[])     {         BufferedReader br = null;         String str = " ";                  System.out.println("Enter the file path");         br = new BufferedReader(new InputStreamReader(System.in));                  try         {             str = br.readLine();             }         catch(IOException e)         {             e.printStackTrace();         }                  try         {             String s;                          // file resource             br = new BufferedReader(new FileReader(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

The above method using try-catch-finally is unnecessarily complicated with nested try blocks. This can be simplified using the try-with-resources method by containing all the statements in the nested try blocks from the above code into a single try block.

In the try-with-resources method, there is no use of the 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 the AutoCloseable interface, and those objects should also be local. The resource will be closed automatically regardless of whether the 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: 

static String readFirstLineFromFile(String path) throws IOException {     try (BufferedReader br = new BufferedReader(new FileReader(path)))     {         return br.readLine();     } }

Example

Java
// Java program to illustrate // Automatic Resource Management // in Java without finally block  import java.io.*; import java.util.*;  class Resource {     public static void main(String args[])     {         String str = "";         BufferedReader br = null;          System.out.println("Enter the file path");         br = new BufferedReader(             new InputStreamReader(System.in));          try {             str = br.readLine();         }         catch (IOException e) {             e.printStackTrace();         }          // try with Resource         // note the syntax difference         try (BufferedReader b              = new BufferedReader(new FileReader(str))) {             String s;             while ((s = b.readLine()) != null) {                 System.out.println(s);             }         }         catch (IOException e) {             e.printStackTrace();         }     } } 

Output:

hello  java

Automatic Resource Management in multiple resources

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
// Java program to illustrate // Automatic Resource Management // in Java with multiple resource  class Resource {     public static void main(String s[])     {         // note the order of opening the resources         try (Demo d = new Demo(); Demo1 d1 = new Demo1()) {             int x = 10 / 0;             d.show();             d1.show1();         }         catch (ArithmeticException e) {             System.out.println(e);         }     } }  // custom resource 1 class Demo implements AutoCloseable {     void show() { System.out.println("inside show"); }     public void close()     {         System.out.println("close from demo");     } }  // custom resource 2 class Demo1 implements AutoCloseable {     void show1() { System.out.println("inside show1"); }     public void close()     {         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 the special try-with-resource block, immediately after finishing the try block, JVM calls this.close() method on all resources initialized in the try block. 

Important Points: 

  1. The finally blocks were used to clean up the resources before Java 7.
  2. After java 7, resource cleanup is done automatically.
  3. ARM is done when you initialize resources in the try-with-resources block because of the interface AutoCloseable. Its close method is invoked by JVM as soon as the try block finishes.
  4. Calling the close() method might lead to unexpected results.
  5. A resource that we use in try-with-resource must be subtypes of AutoCloseable to avoid a compile-time error.
  6. The resources which are used in multiple resource ARM must be closed in reverse order as given in the above example

 


Next Article
Automatic Resource Management in Java ( try with resource statements )

K

kartik
Improve
Article Tags :
  • Technical Scripter
  • Java
Practice Tags :
  • Java

Similar Reads

    CRUD Operations in Student Management System in Java
    CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a develop
    7 min read
    Try-with-resources Feature in Java
    In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource.  The try-with-resources statement ensures that each re
    4 min read
    Demystifying Memory Management in Modern Java Versions
    Memory management is the backbone of Java programming, determining how efficiently your applications use system resources. In this comprehensive guide, we will explore the intricacies of memory management in modern Java versions, including Java 8, 11, and beyond. By the end of this article, you'll h
    6 min read
    ResourceBundle and ListResourceBundle class in Java with Examples
    The ResourceBundle and ListResourceBundle classes are part java.util package. These classes are designed to aid in the internationalization of programs. ResourceBundle: The class ResourceBundle is an abstract class. It defines methods that enable you to manage a collection of locale-sensitive resour
    4 min read
    Standard Practices for Protecting Sensitive Data in Java
    The Java platform provides an environment for executing code with different permission levels and a robust basis for secure systems through features such as memory safety. The Java language and virtual machine make application development highly resistant to common programming mistakes, stack smashi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences