0

I see that try-with-resources is available to any class that implements the AutoCloseable interface.

public interface AutoCloseable {
  void close() throws Exception;
}

Is that the only criteria for a class to support try-with-resources in Java (I meant, are there any possible scenarios where a class doesn't implement AutoCloseable interface but supports try-with-resources)?

Aaditya Sharma
  • 3,330
  • 3
  • 24
  • 36
  • `AutoCloseable` is a .NET-twin of `IDisposable`, have a look how the C# world uses duck typing: https://stackoverflow.com/questions/6368967/duck-typing-in-the-c-sharp-compiler – terrorrussia-keeps-killing Dec 23 '20 at 19:21

1 Answers1

4

From §14.20.3 of the Java Language Specification:

The type of a variable declared or referred to as a resource in a resource specification must be a subtype of AutoCloseable, or a compile-time error occurs.

In other words, only instances of AutoCloseable can be used with try-with-resources.


Note on terminology (also explained in the same section of the JLS). If you have:

try (AutoCloseable foo = ...;
     AutoCloseable bar = ...) {
  // do stuff...
} catch (Exception ex) {
  // handle exception...
}

Then the "resource specification" is:

(AutoCloseable foo = ...;
 AutoCloseable bar = ...)

And there are two "resources": foo and bar.

Slaw
  • 37,820
  • 8
  • 53
  • 80