Pankaj Shinde
Pankaj Shinde

Reputation: 3689

Why java.lang.AutoCloseable interface is added in Java 1.7

java.lang.AutoCloseable interface is same as java.io.Closeable interface. So what is need to add new java.lang.AutoCloseable interface in Java 1.7.

Upvotes: 1

Views: 826

Answers (2)

Aakash Sirohi
Aakash Sirohi

Reputation: 23

Let us consider the following piece of code :

try(Resource1;Resource2;Resource3){
  // Your Code Here
}

Now, we can take IO related resources, Network related resources or Database related resources.

  1. All of these resources should be AutoCloseable resources. Which means that the corresponding classes of these resources should implement AutoCloseable interface.

  2. All of these resources already implement the AutoCloseable Interface.

  3. AutoCloseable interface was introduced in 1.7 version of Java.

  4. This interface only has one method that is-

    public void close(){}

Upvotes: -1

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32478

in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource 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).

It's used for auto closing the resources regardless of whether the try statement completes normally or abruptly in Java 7, check here for more details.

And,

The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

Upvotes: 1

Related Questions