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?
I'm sure most people are aware of it, but since this question is still among the top results when searching for "IDisposable Java" (#2 result for me just now), and it's still not mentioned here...
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.