w3resource logo
Redis Tutorial

Try with resource feature of Java 7

Introduction

Java 7 introduce new language feature called try-with-resource statement. Generally, we see database connection statement, resultset, File IO streams etc operated inside try-block because checked exception declared inside it. Before Java 7, we might write code to close these resources in finally block. Sample code below explains without this feature (This is valid way to write but not much readable code)

Java Code: 

package trywithresource;
public class TryCatchFinally {
	public void Demo() {
		try {
			// create resource statements
		} catch (Exception e) {
			// Handle the Exceptions
		} finally {
			//if resource is not null
			try{
				//close the resources
			}catch (Exception resourceClosingExp){
			}
		}
	}
}

We have to explicitly close the resource and thereby add a few more lines of code. There are few cases where the developer will forget to close the resource and this will introduce memory leak and performance impact in a large application. So to overcome these and other issues – try-with-resources is introduced in Java 7. To understand the resource handling let's take an example. Here in below program, we are defining two custom exceptions (ExceptionA and ExceptionB). We also have myResource class which has two methods doSomeWork() and closeResource(), here both methods throws checked exceptions which need to be handled by calling class. We have a main class which is creating an object of myResource and calling method doSomeWork(). Inside finally block it is closing the resource.

while loop image-1

Java Code: 

package trywithresource;
public class MyResource {
        public void doSomeWork(String work) throws ExceptionA{
            System.out.println("Doing: "+work);
            throw new ExceptionA("Exception occured while doing work");
        }
        public void close() throws ExceptionB{
            System.out.println("Closing the resource");
            throw new ExceptionB("Exception occurred while closing");
        }
}

Java Code: 

package trywithresource;
public class OldTryDemo {
	public static void main(String[] args) {
		MyResource res = null;
		try {
			res = new MyResource();
			res.doSomeWork("Writing an article");
		} catch (Exception e) {
			System.out.println("Exception Message: " + e.getMessage()
					+ " Exception Type: " + e.getClass().getName());
		} finally {
			try {
				res.close();
			} catch (Exception e) {
				System.out.println("Exception Message: " + e.getMessage()
						+ " Exception Type: " + e.getClass().getName());
			}
		}
	}
}

Output:

while loop image-1

As you can see 21 lines of code and readability of code decreased. Now let’s implement the same program using Java 7’s try-with-resource construct. For this, we would need a new resource – NewResource. In Java 7 a new interface has been introduced named java.lang.AutoCloseable. Those resources which need to be closed automatically implement this interface. All the older IO APIs, socket APIs etc. implement the Closeable interface – which means these resources can be closed.

With Java 7, java.io.Closeable implements AutoCloseable. So everything works without breaking any existing code.

Java Code: 

package trywithresource;
public class NewResource implements AutoCloseable {
	String closingMessage;
	public NewResource(String closingMessage) {
		this.closingMessage = closingMessage;
	}
	public void doSomeWork(String work) throws ExceptionA {
		System.out.println(work);
		throw new ExceptionA("Exception thrown while doing some work");
	}
	public void close() throws ExceptionB {
		System.out.println(closingMessage);
		throw new ExceptionB("Exception thrown while closing");
	}
	public void doSomeWork(NewResource res) throws ExceptionA {
		res.doSomeWork("Wow res getting res to do work");
	}
}

Java Code: 

package trywithresource;
public class TryWithResource {
	public static void main(String[] args) {
		try (NewResource res = new NewResource("Res1 closing")) {
			res.doSomeWork("Listening to podcast");
		} catch (Exception e) {
			System.out.println("Exception: " + e.getMessage() + " Thrown by: "
					+ e.getClass().getSimpleName());
		}
	}
}

Output:

while loop image-1

One thing to note above is that the Exception thrown by the close is being suppressed. So you can right away notice the difference between the two implementations, one using try…catch…finally and the other using try-with-resource. In the example above only one resource is declared as used. One can declare and use multiple resources within the try block, also nest these try-with-resources blocks.

Summary:

  • Try-with-Resource is additional functionality introduce in Java 7 to make code development easier but it is not mandatory to use, we can continue using try-catch-finally block as well.
  • Try-with-Resource will make code the more readable which means easy to understand and manage.

Java Code Editor: