Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 948
Daniel Fortunov Avatar asked Jul 22 '09 13:07

Daniel Fortunov


People also ask

Does Java have IDisposable?

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 .

How do you use AutoCloseable in Java?

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.


2 Answers

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.

like image 170
Paul Groke Avatar answered Sep 25 '22 01:09

Paul Groke


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(); } 
like image 24
Zarkonnen Avatar answered Sep 25 '22 01:09

Zarkonnen