Why Java7 introduces AutoCloseable specially? [closed]
Asked Answered
C

2

11

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?

Catatonia answered 11/11, 2014 at 13:44 Comment(0)
K
12

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.

Kavanagh answered 11/11, 2014 at 13:48 Comment(2)
Thank you very much!!I think the first reason is more persuasive. It will be great if you can update your answer and give us an example of resource whose close() does not throws IOException.Catatonia
@Jaskey: ResultSet is a good example, where close() throws SqlException.Kavanagh
P
1

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.

Prolix answered 11/11, 2014 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.