Java - AutoCloseable Interface

In this post, we will discuss the AutoCloseable interface in Java with an example.
  • The AutoCloseable interface provides support for the try-with-resources statement, which implements what is sometimes referred to as automatic resource management.
  • The try-with-resources statement automates the process of releasing a resource (such as a stream) when it is no longer needed.
  • AutoCloseable is implemented by several classes, including all of the I/O classes that open a stream that can be closed.
The close() method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header. This construction ensures prompt release, avoiding resource exhaustion exceptions and errors that may otherwise occur.
The AutoCloseable interface defines only the close( ) method, which is shown here:
public interface AutoCloseable {
    void close() throws Exception;
}

AutoCloseable Interface Example

In this example, we will use a BufferedReader internally implements the Closeable interface, which extends the AutoCloseable interface. The close() method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header hence the BufferedReader resource class is automatically closed by calling close() method of an AutoCloseable object. 
The class diagram shows the hierarchy of the BufferedReader class:

The following example reads the lines from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it. 
public class BufferedReaderExample {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("C:/workspace/java-io-guide/sample.txt");
            BufferedReader br = new BufferedReader(fr);) {
            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
BufferedReader instance is declared in a try-with-resources statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Learn more examples of AutoCloseable interface at The try-with-resources Statement with Examples.

Comments