Wednesday, 7 October 2020

What Is The Actual Difference Between Closeable And AutoCloseable In Java

Well, practically there is not much difference. If you check Java doc, you will notice that Closeable interface extends AutoCloseable interface. But there is one difference & that explains the reason why AutoCloseable interface was introduced in Java 7. Closeable  close() method can throw IOException only. And that made  sense as you will be using Closeable mostly with IO resources. But to handle other generic exceptions too with close() method, AutoCloseable was introduced.


public interface Closeable extends AutoCloseable {

              public void close() throws IOException;

}

public interface AutoCloseable {

                void close() throws Exception;

}

There is a misconception that Closeable can't be used with try-with-resources code block. But that is not true from Java 7 & hopefully everybody has a more upgraded version than that 😀. Both interfaces work with try-with-resources statement so that you don't have to call close() method explicitly.

No comments:

Post a comment

How To Solve "Caused by: org.hibernate.HibernateException: Missing table" When Table Is Present In Database

If you are using JPA or Hibernate directly and got that exception while starting your application, there is one obvious reason for that. You...