Sobes.tech
Senior

What is the difference between AutoCloseable and Closeable?

sobes.tech AI

Answer from AI

The Closeable and AutoCloseable interfaces in Java are used for automatic resource management but have some differences:

  • Closeable is in the java.io package and is intended for input/output streams. The close() method in this interface is declared to throw IOException.
  • AutoCloseable was introduced in Java 7 in the java.lang package and is more general. The close() method can throw any exception (Exception).

Closeable extends AutoCloseable, meaning all Closeable are AutoCloseable, but not vice versa.

This is important when using try-with-resources: if the resource implements Closeable, then the close exceptions are limited to IOException, but if only AutoCloseable, any exception can be thrown.

Example:

class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Closing resource");
    }
}

try (MyResource r = new MyResource()) {
    // work with the resource
}