Both are interfaces used to close resources. Closeable was introduced with JDK5 and now it looks as follows:
public interface Closeable extends AutoCloseable { public void close() throws IOException; }
AutoCloseable was introduced with JDK7 and looks as follows:
public interface AutoCloseable { void close() throws Exception; }
Closeable has some limitations, as it can only throw IOException, and it couldn't be changed without breaking legacy code. So AutoCloseable was introduced, which can throw Exception. If you use JDK7+, you are supposed to use AutoCloseable. As JDK7+ libraries use AutoCloseable and legacy code that implements Closeable still need to work with JDK7+, the solution was having Closeable extend AutoCloseable.
AutoCloseable was specifically designed to work with try-with-resources statements. As Closeable extends AutoCloseable, you can use try-with-resources to close any resources that implement either Clseable or AutoCloseable:
try(FileInputStream fin = new FileInputStream(input)) { // Some code here }
However, if you have a resource that doesn't implement any of them, you still have to use a finally block, like in the old days:
Resource r = new Resource(); try()) { // Some code here } finally { r.close(); }
Note that Closeable is idempotent, that means that calling the method close() more than once has no side effects.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.