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?
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 .
The Closeable interface extends AutoCloseable interface therefore any class that implements Closeable also implements AutoCloseable. The close() method is invoked to release resources that the object is holding. If the stream is already closed then invoking the close method does not have any effects.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With