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
?
Closeable
is restricted to throwIOException
, which may not be appropriate for some closeable but non-IO-bound resources.AutoCloseable
is declared to throwException
, making it more general-purpose.The API for
Closeable
can't be changed to throwException
as that would be a breaking change, hence the new superinterface.Additionally, as documented:
So while every
Closeable
isAutocloseable
, the reverse is not true, and it would have been limiting to restrict try-catch-finally to the semantics ofCloseable
.