• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on closing wrapped streams

 
Ken Pelletier
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've read two opposing views on what's required when closing wrapped streams, and I'd like to get to the bottom of it.
One view is that each stream has to be closed explicitly, in the opposite order that they were opened.
The opposing view is that closing the outer-most stream is all that's needed; it calls close() on all wrapped streams recursively.
Example:

Much of the code I read doesn't make the inner close ( fis ), but I keep reading in places that it is required.
What's the skinny?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you've shown it, no, the second close doesn't actually do anything useful. Closing any filter stream automatically closes the inner stream. (Same for readers and writers.) Most of the time this is good enough. Where you may have trouble though, is if you're trying to do robust exception handling. If something goes wrong while you're working with this file, you may well need to make sure the file does indeed get closed, even while you're throwing an exception from the method.
As an example, let's say that if any error occurs while processing this file, you need to delete the file as part of the cleanup. (Or move it to another directory.) If a FileInputStream is still open when File delete() is called, the delete will probably fail. Same for File moveTo(). So it's in your interest to make sure the file is closed as soon as the exception is thrown:

If an exception is thrown, it will be thrown out of this method entirely. But not before any open streams are closed. Note that fis and dis are guaranteed to be non-null at the points where I close them.
This sort of structure starts looking pretty complex if you've got multiply nested streams you want to close - which is why it's a good idea to make processDataInputStream() a separate method, to reduce clutter. Of course, we'd use better method names if we knew what sort of "processing" needed to be done...
[ August 20, 2002: Message edited by: Jim Yingst ]
 
Ken Pelletier
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! Excellent reply; clears up a lot.
As I'd suspected, there seems to be a lack of understanding showing through in a lot of code that I read. I've see a lot of unnecessary nested closes which are not motivated by exception handling concerns.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!