1. Introduction
In this article, we are going to present how Closeable
and AutoCloseable
interfaces work in Java.
2. Implementing AutoCloseable
interface
The 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 AutoCloseable
interface:
We created simple class MyCustomResource
that implements AutoCloseable
interface. Now we can use it in try-with-resources
block like the following:
3. Implementing Closeable
interface
The 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 AutoCloseable
or Closeable
interface in Java.
4. Conclusion
In this article, we showcased two interfaces from Java IO: AutoCloseable
and 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 close()
in Closeable
interfaces throws IOException
and AutoCloseable.close()
method throws Exception
class.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}