In this article, we are going to present how
AutoCloseable interfaces work in Java.
AutoCloseable interface is used for resources that need to be closed after they are not needed anymore. The
close() method from this interface is called automatically by JVM when exiting a try-with-resources block.
Let's have a loot at a simple example of using
We created simple class
MyCustomResource that implements
AutoCloseable interface. Now we can use it in
try-with-resources block like the following:
Closeable is an older interface that was introduced to preserve backward compatibility. It extends
AutoCloseable interface. The implementation of the
close() method should release any system resources.
As you can see there is no difference between implementing
Closeable interface in Java.
In this article, we showcased two interfaces from Java IO:
Closeable. Both are used to release resources after the
try-with-resources block ends. The
Closeable is the old one that exists only to preserve backward compatibility. The method
Closeable interfaces throws
AutoCloseable.close() method throws