Resources closed by callee - good or bad pattern?

I recently came across an API where I have to pass an InputStream as one of the parameters. Surprisingly, the InputStream was closed by the callee when EOF was reached. Since I passed an InputStream for a zip entry derived from a ZipInputStream the entire ZipInputStream was closed making it impossible to read further entries.

As far as I got it, it should be good practice for a callee not to close any resources passed as a parameter (this should also be true for JDBC Connection and the like). I would like to learn what the communities opinion is about this topic.

Thanks

Richard

[609 byte] By [richardbirenheidea] at [2007-10-2 2:38:12]
# 1

I tend to agree; however, there are so many API's that do close streams when finished that I have gotten used to it. The one caveat I would make is that the Javadocs or other documentation should clearly state that the stream will, in fact, be closed at the end of the operation. You can always subclass FilterOutputStream or FilterInputStream and override close() to not actually close the underlying stream. Then add a closeFinal() or some similarly named method to actually close the underlying stream.

- Saish

Saisha at 2007-7-15 20:30:23 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

> You can always

> subclass FilterOutputStream or FilterInputStream and

> override close() to not actually close the underlying

> stream. Then add a closeFinal() or some similarly

> named method to actually close the underlying

> stream.

Or create a wrapper stream.

dubwaia at 2007-7-15 20:30:23 > top of Java-index,Other Topics,Patterns & OO Design...
# 3
I've already thought about creating a wrapper stream for my concrete problem. But anyway, what I would like to find out is what the community thinks about the underlying problem: is it good practice that a callee frees resources it gets as a parameter?
richardbirenheidea at 2007-7-15 20:30:23 > top of Java-index,Other Topics,Patterns & OO Design...
# 4
If you didn't open it you shouldn't close it.
_dnoyeBa at 2007-7-15 20:30:23 > top of Java-index,Other Topics,Patterns & OO Design...
# 5
I agree. But always read the API docs. Xalan, in particular, seems to enjoy closing streams that are passed to it. And that's a fairly accepted API that developers may regularly use.- Saish
Saisha at 2007-7-15 20:30:23 > top of Java-index,Other Topics,Patterns & OO Design...
# 6
One idea I've played around with is for classes that accept a stream to take a parameter that flags whether the caller would like the stream to be closed when the callee is finished.
dubwaia at 2007-7-15 20:30:23 > top of Java-index,Other Topics,Patterns & OO Design...