Java AutoCloseable interface
Autocloseable
interface in java is an interface that is used to indicate that a resource can be automatically closed by the JVM. This is useful for resources that need to be released when they are no longer needed, such as file handles or database connections.
java.lang.AutoCloseable
interface is added in java 7 and it works with try-with-resources, which was also introduced in java 7.
try-with-resources
allows you to automatically close resources that are opened in a try
block. These resources must implement AutoCloseable
.
Java docs for AutoCloseable
state,
The
close()
method of anAutoCloseable
object is called automatically when exiting atry-with-resources
block for which the object has been declared in the resource specification header
AutoCloseable
interface defines a single method, close()
, which takes no arguments and returns no value. This method is called automatically when the resource is no longer needed, and it is the responsibility of the implementer to ensure that the resource is properly cleaned up.
Below is a resource that implements
AutoCloseable
interface and its close()
method. class MyReader implements AutoCloseable { @Override public void close() throws Exception { System.out.println("Close called for " + this.getClass().getName()); } }
Now, an object of this class can be used in try-with-resources
as shown below
try (MyReader reader = new MyReader()) { // code } catch (Exception e) { e.printStackTrace(); }
As try
block is completed, below message is printed
Close called for com.codippa.MyReader
This means that close()
is automatically called when try-with-resources
exits.
If you use a resource, in try-with-resources
that does not implement AutoCloseable
, then a compiler error will be raised as below
The resource type MyReader does not implement java.lang.AutoCloseable
AutoCloseable in java api
All the resources that need to be closed after their use implement AutoCloseable
.
Examples of these resources are
java.sql.Connection
: represents a database connection.
Readers such as FileReader
, BufferedReader
etc.
Streams such as FileInputStream
, FileOutputStream
etc.
java.io.Closeable
, which represents a resource that should be closed extends AutoCloseable
and all resources mentioned above implement Closeable
.
This means that all the resources that you could close in finally
block, they can also be used in try-with-resources
.
That is all on AutoCloseable
interface in java. Hope the article was useful.