Closeable vs AutoCloseable

August 25, 2020 No comments Java IO Java Closeable AutoCloseable

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:

package com.frontbackend.java.io.trywithresources;

public class MyCustomAutoCloseableResource implements AutoCloseable {

    @Override
    public void close() throws Exception {
        // close resource
    }
}

We created simple class MyCustomResource that implements AutoCloseable interface. Now we can use it in try-with-resources block like the following:

try (MyResource res = new MyResource()) {
    // use resource here
}

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.

package com.frontbackend.java.io.trywithresources;

import java.io.Closeable;
import java.io.IOException;

public class MyCustomCloseableResource implements Closeable {

    @Override
    public void close() throws IOException {
        // close resource
    }
}

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.

{{ message }}

{{ 'Comments are closed.' | trans }}