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

Daniel Fortunov picture Daniel Fortunov · Jul 22, 2009 · Viewed 15.9k times · Source

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?

Answer

Paul Groke picture Paul Groke · Mar 16, 2013

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.