Try with Resource Example – Java 7 Feature for automatic resource management

One of the Java 7 features is try-with-resources statement for automatic resource management. A resource is an object that must be closed once your program is done using it, like a File resource or JDBC resource for database connection or a Socket connection resource. Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks and performance hit when we forgot to close the resource.

Let’s see a pseudo code snippet to understand this feature.

Before Java 7:

try{
	//open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
	// Exception handling like FileNotFoundException, IOException etc
}finally{
	// close resources
}

Java 7 implementation:

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
	// exception handling
}
// resources are closed as soon as try-catch block is executed.

Let’s write a simple program to read a file and print the first line using Java 6 and older versions and Java 7 try-with-resources implementation.

Java 6 Resource Management Example

package com.journaldev.util;

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

public class Java6ResourceManagement {

	public static void main(String[] args) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("C:\\journaldev.txt"));
			System.out.println(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}

Java 7 Try With Resource Automatic Resource Management

package com.journaldev.util;

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

public class Java7ResourceManagement {

	public static void main(String[] args) {
		try (BufferedReader br = new BufferedReader(new FileReader(
				"C:\\journaldev.txt"))) {
			System.out.println(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Benefits of using try with resources

  • More readable code and easy to write.
  • Automatic resource management.
  • Number of lines of code is reduced.
  • No need of finally block just to close the resources.
  • We can open multiple resources in try-with-resources statement separated by a semicolon. For example, we can write following code:
    try (BufferedReader br = new BufferedReader(new FileReader(
    				"C:\\journaldev.txt"));
    				java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(FileSystems.getDefault().getPath("C:\\journaldev.txt"), Charset.defaultCharset())) {
    			System.out.println(br.readLine());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
  • When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue. You can extend my resource program to prove that.

Java 7 has introduced a new interface java.lang.AutoCloseable which is extended by java.io.Closeable interface. To use any resource in try-with-resources, it must implement AutoCloseable interface else java compiler will throw compilation error.

Lets confirm this with an example:

package com.journaldev.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;

public class Java7ResourceManagement {

	public static void main(String[] args) {

		try (MyResource mr = new MyResource()) {
			System.out.println("MyResource created in try-with-resources");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Out of try-catch block.");
	}

	static class MyResource implements AutoCloseable{

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyResource");
		}

	}
}

Output of above program is:

MyResource created in try-with-resources
Closing MyResource
Out of try-catch block.

From the output it’s clear that as soon as try-catch block is finished, resource close method is called.

There is one difference to note between try-catch-finally and try-with-resources in case of exceptions. If exceptions are thrown in both try block and finally block, the method returns the exception thrown in finally block whereas if exception is thrown in try block and in try-with-resources statement, then method returns the exception thrown in try block.
To better clarify this difference, we will see a sample code.

package com.journaldev.util;

public class Java7ResourceManagement {

	public static void main(String[] args) throws Exception {
		try {
			tryWithResourceException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		try {
			normalTryException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	private static void normalTryException() throws Exception {
		MyResource mr = null;
		try {
			mr = new MyResource();
			System.out.println("MyResource created in try block");
			if (true)
				throw new Exception("Exception in try");
		} finally {
			if (mr != null)
				mr.close();
		}

	}

	private static void tryWithResourceException() throws Exception {
		try (MyResource mr = new MyResource()) {
			System.out.println("MyResource created in try-with-resources");
			if (true)
				throw new Exception("Exception in try");
		}
	}

	static class MyResource implements AutoCloseable {

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyResource");
			throw new Exception("Exception in Closing");
		}

	}
}

Output of the above program is:

MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing

The output of the program proves the difference given above. Thats all for the try-with-resources, I will be writing more on java 7 features in near future.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Today's Special: Java Persistence API PDF eBook Free Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now