Using AutoCloseable with 'try-with-resources'

Java 7’s new ‘try-with-resources’ feature helps developers by automatically closing the resources used in a program. It not only works with Java’s build in types but can also work with custom types. Java 7 added the java.lang.AutoCloseable interface that developers can implement in their custom classes for using them with try-with-resources.

In this article we will learn about AutoCloseable interface and create a custom AutoCloseable implementation. If you wish to learn about try-with-resources in details check this article.


AutoCloseable Interface

AutoCloseable interface has only a single method called close(). Shown below is how the AutoCloseable interface looks like:

public interface AutoClosable {
    public void close() throws Exception;
}

Sample Code

Let’s create a simple AutoCloseable implementation to understand it better. The code below shows a simple AutoCloseable implementation:

package cubearticle.examples.test;

public class DemoAutoCloseable implements AutoCloseable{

    @Override
    public void close() throws Exception {
	System.out.println("Closing Autocloseable Resource");
    }
	
    public void open(){
	System.out.println("Opening AutoCloseable Resource");
    }
}

Other than providing a concrete implementation for the close() method, we also defined an open() method. This method can be used to open the autocloseable resource and do some processing (an Autocloseable that does nothing but just closes is of no use), though we are not doing any actual processing here.

Now that we have successfully written our custom Autoclosable implementation, we need a TestClass for executing it.

package cubearticle.examples.test;

public class TestClass {
	
    public static void main(String[] args){
    		
        try(DemoAutoCloseable demoAutoCloseable = new DemoAutoCloseable();){
	    demoAutoCloseable.open();
        }
	catch (Exception e) {
            e.printStackTrace();
	}
    }
}

Below is the output generated on executing our test class:

Opening AutoCloseable Resource
Closing Autocloseable Resource

We can see that our close() method of our custom Autocloseable implementation is automatically executed, even though we did not call it in our test program.

RELATED ARTICLES

2 ways to Create a Thread in Java

Threads in Java can be created in 2 different ways, extending the Thread class and implementing the Runnable interface. This article explains the two ways with suitable examples.

View Article

4 Different Ways of Creating an Object in Java

Most of us have created object using new operator in Java. Did you know the other ways to create objects in Java. This article talks about 4 different ways of creating objects in Java.

View Article

Chained Exception

Chained exception is a feature introduced with JDK 1.4, which allow developers to associate an exception with another exception.

View Article

Shallow Cloning and Deep Cloning

Cloning an object can happen in two ways Deep and Shallow Cloning. In shallow cloning only object references are copied while in deep copy actual objects are copied to the newly cloned object.

View Article

Exception Handling in Inheritance

There are certain rules that must be followed while throwing exceptions in inheritance and overriding methods. This article discuss about these rules.

View Article

Garbage Collection in Java

Java Garbage Collector is a boon to Java developers; it allows developers to program without worrying about memory management. This article describes the working of Java Garbage Collector in details.

View Article

Understanding static and final in Java

Java provides various modifiers which when used with variables, methods or classes, provides them with special properties. Static and final are are two such modifiers which are used frequently by Ja..

View Article

Understanding Object Cloning

Java provides the clone() method which can be used to create a copy an object. It creates a new memory location and copies the content of the object being cloned into the new location.

View Article

Try-with-resources Statement in Java 7

Java 7 introduces the new 'try-with-resources' statement which help developers to overcome the tedious task of closing the resources that have been used in the program.

View Article

Varargs: Variable Arguments to Methods

Java 5 introduced a new feature called varargs, which allows methods to accept variable number of arguments. They are useful in cases where the number of arguments to be passed to a method is unknown.

View Article