Why is AutoCloseable the base interface for Closeable (and not vice versa)?
@Sotirios Delimanolis's comment has nailed it.
The Java 7 team wanted a mechanism to label objects as be auto-closeable for the "try with resources" construct. Unfortunately the API spec for the Closeable.close()
method is too strict. It requires the close()
method to be idempotent ... but this is not necessary in the "try with resources" use-case.
So they introduced the AutoClosable
interface with a less restrictive close()
semantic ... and retro-fitted Closeable
as a subtype of AutoCloseable
.
The other thing is that AutoCloseable.close()
is declared as throwing Exception
rather than IOException
. This means that the AutoCloseable
API is less restrictive than Closeable
... and given that it is effectively used as a callback API in try-with-resources, this makes it more flexible / more broadly applicable. (The API can be used for resources that have nothing to do with I/O, but still might throw exceptions on close.) The flip-side is that Java typing would not allow them to make such a change if the close() throws Exception
method had been injected into the subtype.
The alternatives would have been:
to restrict "try with resources" to resources with an idempotent close ... which limits its usefulness, or
to retrospectively change the semantics of
Closeable.close()
... which could lead to difficulties for folks porting older code to Java 7to retrospectively change the signature of
Closeable.close()
... which would break binary compatibility.
The Closeable
interface was introduced in Java 5.
When try-with-resources
(below is an example code) was introduced in Java 7, the language designers wanted to change some things but needed backward compatibility (all the code which is written in previous versions should not become obsolete with introduction of new functionalities) also so they created a Superinterface AutoCloseable
with the rules they wanted.
An example of try with resources:
try (NewResource a = NewResource.CreateResource();
{
}
Above code is Try with resources. We can simply understand by this is that in this code we can declare a new variable itself in the try code and that variable can call upon other methods within the code. Apart from decreasing verbosity of try
block this code also does not require a finally block, but the executing environment should be Java 7 or above. Although the finally is created by JVM itself.
closeable
& Autocloseable
interface contains just one method
void close()
While close ()
method of closeable
throws IOException
, Autocloseable
's close()
method throws Exception
.
This way, all the user code which implemented Closeable
automatically gets to implement AutoCloseable
, which allows them to automatically benefit from the try-with-resources syntax.