Tuesday, 28 June 2016

AutoCloseable and Closeable interface in Java : Since: JDK 1.7

java.lang interface AutoCloseable

Closeable extends AutoCloseable, and is specifically dedicated to IO streams.

Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitly.

try(open file or resource here) {
//after try block, file will close automatically.

void close() throws Exception

This method is invoked automatically on objects managed by the try-with-resources statement.

While this interface method is declared to throw Exception, implementer are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.
Throws: Exception - if this resource cannot be closed.

Example of AutoCloseable

class Resource implements AutoCloseable {
      private String value;
      public Resource(String value) {
            this.value = value;
      public void close() throws Exception {
            /* De-reference the unused resource */
            this.value = null;
            System.out.println("Resource closed !!");
      public String getValue() {
            return value;

public class Demo {
      public static void main(String[] args) {

            try(Resource res =new Resource("Resource opened !!")) {
                  String str = res.getValue();
            } catch (Exception e) {
Resource opened !!
Resource closed !!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...