Master java skills

Try With Resources

Managing resources in Java has always been a tedious task for developers. Prior to Java 7, it was necessary to manually close resources such as streams, files, and network connections using a finally block. This approach was prone to errors and often resulted in resource leaks.

To simplify resource management, the “try with resources” statement was introduced in Java 7.

What are Resources in Java?

Resources are any objects that need to be closed after they are no longer needed.

Examples of resources include:

  • Streams
  • Files
  • Network Connections
  • Database Connections.

Failure to close these resources can lead to memory leaks and other issues.

Traditional Approach to Resource Management

Before Java 7, the traditional approach to resource management was to use a try-finally block. In this approach, the resource was declared outside the try block, and a finally block was used to close the resource.

Example of Traditional way of Resource Management:

package com.javatrainingschool;

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

public class TraditionalResourceManagement {

	public static void main(String[] args) {
		FileReader fr = null;  
		
		BufferedReader br = null; 

		try {
			
			fr = new FileReader("inputFile.txt");  
			br = new BufferedReader(fr);   

			String inputFileLine;
			
			// Read each line of the input file using the BufferedReader and print to console
			while ((inputFileLine = br.readLine()) != null) {   
				System.out.println(inputFileLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// The finally block is used to close the resources to avoid resource leaks
		finally {   
			try {
				if (br != null) {
					br.close();
				}
				if (fr != null) {
					fr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

The above program reads lines of text from a file named “inputFile.txt” and prints them to the console. The FileReader and BufferedReader objects are created in the try block, and the readLine() method is called inside a while loop to read each line of text.

The finally method is used to release the resource that we used i.e FileReader & BufferedReader.

Drawbacks of this approach

While this approach works, it can become difficult to handle and error-prone when dealing with multiple resources or when the code becomes more complex. This is where the try-with-resources statement comes in handy as it simplifies resource management and reduces the likelihood of resource leaks.

The “Try with Resources” Statement

The “try with resources” statement automatically closes the resources that are declared in its parentheses. Here’s an example:

package com.javatrainingschool;

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

public class TryWithResourcesDemo {

	public static void main(String[] args) {

		try (FileReader fr = new FileReader("inputFile.txt");
			 BufferedReader br = new BufferedReader(fr)) {

			String inputFileLine;

			// Read each line of the input file using the BufferedReader and print to console
			while ((inputFileLine = br.readLine()) != null) {
				System.out.println(inputFileLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

In this example, the FileReader is declared inside the parentheses of the try statement. The FileReader is automatically closed when the try block is finished, regardless of whether an exception is thrown or not. This approach eliminates the need for a finally block and reduces the amount of code that needs to be written.

Benefits of “Try with Resources”

  1. Simplifies code: The “try with resources” statement simplifies the code by eliminating the need for a finally block. This makes the code easier to read and maintain.
  2. Reduces errors: The “try with resources” statement reduces errors by automatically closing the resources. This eliminates the chances of resource leaks and other issues.
  3. Improves performance: The “try with resources” statement improves performance by eliminating the need for an extra method call to close the resource.
  4. Supports multiple resources: The “try with resources” statement supports multiple resources, which makes it easier to manage multiple resources at the same time.
try (FileReader fr = new FileReader("inputFile.txt");
     BufferedReader br = new BufferedReader(fr);) {
    // use the FileReader here
      } catch (IOException e) {
		   // handle the exception
	          }