Should Closeable be used as the Java equivalent for .NET's IDisposable?

idisposable, java

Solution

Especially given that close() throws an IOException you then have to write exception handling code for, I would advise you write your own interface. This interface can then throw any checked exceptions that are appropriate to the use you want to put the interface to.

Interfaces tend to signify intent in the mind of the reader, so having a class implement an IO-associated Closeable interface will make the reader assume the class is also IO-based.

Obviously, if the objects you do want to close are all IO-related, you should use Closeable. But otherwise go for

/** Interface for objects that require cleanup post-use. Call dispose() in finally block! */
public interface Disposable {
    public void dispose();
}

Problem

Update: As @PaulGroke points out below, things have changed with Java 7: there now is AutoCloseable. Which isn't tied to streams and supported by the new try-with-resources construct. `AutoCloseable` is the direct Java equivalent for .NET's `IDisposable` interface. The `Closeable` interface introduced in Java 1.5 is tightly tied to streams, and even has an exception specifier for `IOException`. This suggests that it should only be used for streams or other IO related activities, rather than general purpose cleanup logic. Certainly the description for the `close()` method would make absolutely no sense outside of a stream/IO context: `void close() throws IOException` Closes this stream and releases any system resources associated with it. Should I therefore declare my own interface, `Disposable`, with a `Dispose()` method on it, and use that as an analogue to .NET's `IDisposable` interface? Or should I re-use `Closeable` even though it may not be a perfect fit?

Original source