Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java7 introduces AutoCloseable specially? [closed]

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?

like image 699
JaskeyLam Avatar asked Nov 11 '14 13:11

JaskeyLam


1 Answers

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.

like image 95
Jon Skeet Avatar answered Oct 18 '22 08:10

Jon Skeet