Why Java7 introduces AutoCloseable specially?

483 views Asked by At

AutoCloseable is introduced in jdk1.7 and Cloesable is already in jdk1.5.

And According to https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

So, the Closeable instance is already can be treated as a resource in try-with-resources statement. This is for sure, since Closeable extends from AutoCloseable.

My question is why java specially introduces AutoCloseable , why don't they only make Closeable to be supported in try-with-resources, is there any other ways for AutoCloseable to be used except for try-with-resources?

2

There are 2 answers

2
Jon Skeet On BEST ANSWER

Closeable is restricted to throw IOException, which may not be appropriate for some closeable but non-IO-bound resources.

AutoCloseable is declared to throw Exception, making it more general-purpose.

The API for Closeable can't be changed to throw Exception as that would be a breaking change, hence the new superinterface.

Additionally, as documented:

Note that unlike the close method of Closeable, this close method is not required to be idempotent. In other words, calling this close method more than once may have some visible side effect, unlike Closeable.close which is required to have no effect if called more than once. However, implementers of this interface are strongly encouraged to make their close methods idempotent.

So while every Closeable is Autocloseable, the reverse is not true, and it would have been limiting to restrict try-catch-finally to the semantics of Closeable.

0
biziclop On

The difference between the two is that classes implementing Closeable must guarantee that invoking close() multiple times has no side-effects. There's no such restriction on AutoCloseable.

In practice this means that everything should be Closeable but those classes that would need to be retrofitted can choose the less restrictive AutoCloseable.