Java try-with-resources with Example

Introduced in Java 7, the try-with-resources statements allow us to declare AutoCloseable resources to be used in a try block with the guarantee that the resources will be closed after the execution of try block.

1. Old Approach (Before Java 7)

Before Java 7, if we had to open a resource, we had to use the try-catch-finally block. We opened the resource in try block and closes it in the finally block. The finally block is guaranteed to be executed by the JVM, so we knew that the resource will be closed even if we get an exception in the try block.

In the following example, we are reading a file line by line using the BufferedReader. Notice how we open the reader in try block and then close it in the finally block.

BufferedReader br = null;

try {
	String sCurrentLine;
	br = new BufferedReader(new FileReader("C:/temp/test.txt"));
	while ((sCurrentLine = br.readLine()) != null) {
		System.out.println(sCurrentLine);
	}
} catch (IOException e) {
	//handle exception
} finally {
	try {
		if (br != null)
			br.close();
	}
	catch (IOException ex) {
		ex.printStackTrace();
	}
}

In the above example, the finally block is a standard implementation for closing a resource. Don’t you think the finally block is unnecessary when we know, we have to close the resource anyway without any oddity??

2. Try-with-resources

Let’s rewrite the previous example with the new try-with-resources syntax. See how much cleaner the code is.

try (BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt"))) {
	String sCurrentLine;
	while ((sCurrentLine = br.readLine()) != null) {
		System.out.println(sCurrentLine);
	}
}
catch (IOException e) {
	//handle exception
}

There are two things to watch closely:

  • The file resource (BufferedReader) is opened in the try block in a special manner (inside small brackets).
  • The finally block is completely gone.

One important thing is that we are not supposed to manually call the close() method. This should be called automatically by JVM. Calling the close() method manually may cause unexpected results.

3. How it works?

Java 7 introduced a new super interface java.lang.AutoCloseable that may hold resources (such as file or socket handles) until it is closed. This interface has a single method close() that is called automatically when exiting a try for which the object has been declared.

void close() throws Exception;

For example, BufferedReader has implemented close() method file this:

public void close() throws IOException {
	synchronized (lock) {
		if (in == null)
			return;
		in.close();
		in = null;
		cb = null;
	}
}

Java docs recommend this interface to be implemented on any IO-based resource that must be closed when it is no longer needed.

4. Conclusion

Let’s recap the highlights point by point:

  • Before java 7, we had to use finally blocks to cleanup the resources. The finally blocks were not mandatory, but resource cleanup was to prevent the system from being corrupt.
  • With Java 7, no need for explicit resource cleanup. It is done automatically when using try-with-resources statement.
  • Cleanup happens because of the new interface AutoCloseable. Its close() method is invoked by JVM as soon as the try block finishes.

Happy Learning !!

Comments

Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode