Closing Streams in Java
Asked Answered
U

6

52

Why do we need to close a FileInputStream (and streams in general) in any case before we leave the program? What would happen otherwise? If the program stops before the input stream is closed explicitly in the program, doesn't the stream also close automatically?

Ulrika answered 5/2, 2009 at 13:55 Comment(1)
Lots of comments sound like "why you won't close the stream" but I think your question was not about "why" but rather "why explicity".Mella
B
45

File handles are scarce, finite resources. You can run out of them if you don't clean them up properly, just like database connections.

If you've written a small program with just one user you can get away with being sloppy and not closing in a finally block.

But if you end up using that idiom in an application that has many users and file handles you might have a problem.

"First we make our habits, then they make us." I try to apply best practices even when they aren't necessary.

Bahrain answered 5/2, 2009 at 13:58 Comment(4)
nice explained. ThanksTimms
I'm definitely going to recycle the habit wisdom. That's a quotable quote right there.Inchoate
That quotable quote ("First we make our habits, then they make us.") is from Stephen Covey.Hustings
11 years late and wrong. Attributed to John Dryden, a poet who died in 1700. Covey isn't that smart. quoteinvestigator.com/2016/12/19/habits-makeBahrain
M
36

Yes, when the process terminates the unmanaged resources will be released. For InputStreams this is fine. For OutputStreams, you could lose an buffered data, so you should at least flush the stream before exiting the program.

Mckamey answered 5/2, 2009 at 13:57 Comment(6)
And what about when the stream object is going out of scope (and garbage-collected)? Will it be closed?Unthinking
@Zippo: Just because a variable goes out of scope doesn't mean the object will be garbage collected. Garbage collection is non-deterministic. Some streams may have a finalizer which will flush them - but it would be a very bad idea to rely on that, IMO.Mckamey
So when using Thread.stop() in Java is easy but almost useless when the thread uses streams... Thanks for info.Unthinking
@Zippo: Thread.stop() is deprecated anyway, as it's generally a bad idea to stop a thread rather than ask it to stop itself in a controlled way.Mckamey
Java 8 will have some features where you can have streams automatically closed upon exiting a scope, comparable to how monitor locks are realease upon exiting a synchronized block.Mella
@UstamanSangat: It's in Java 7, actually: docs.oracle.com/javase/tutorial/essential/exceptions/… (Assuming that's the feature you mean...)Mckamey
L
29

Dude. If you don't close your stream, your unit test will fail. Or at least, it should. So, that's why you need to close it. ;)

And while the OS will almost certainly clean up if you just exit, they'll generally get freed up faster if you explicitly close them. Furthermore, what if your code ends up in a long-running program sometime down the road? Then they'll have problems and curse you. :(

So, it's like washing your hands after using the bathroom. Eventually someone will pay the price if you don't do it. You can get away with it for a while, but it's still a good practice.

Locklin answered 5/2, 2009 at 14:4 Comment(4)
Just curious, why is this voted down? Seems like a good answer to me although funny :)Ironmaster
Naturally, I'd to know, too. :) But maybe the commenter just didn't appreciate that the answer is informative AND humorous.Locklin
I don't know either. For me it was helpful.Ulrika
Personally, because the answer has virtually no technical content -- it would have been a better comment. It doesn't have much more to say than "it's a good practice", and while we often accept such explanations for expediency in our projects, it's not a good enough answer for Stack Overflow. No personal offence meant to you, Don; I'm sure you know what you're talking about, but I prefer answers with more meat.Candlefish
I
10

In addition to Jon's answer, it is generally a good idea to close any resource.

Think of a database connection. Your database cannot have infinite connections opened, in this case when you don't need it, it's better you close it as soon as you're done with it.

It is also good to make this a habit. "finally" block is your friend. In case of C++, you can also use RAII to manage this automatically.

Ironmaster answered 5/2, 2009 at 13:58 Comment(2)
And Java 8 is supposed reduce the boiler plate involved with finally.Mella
Java 7 actually, the java.io.AutoCloseableMella
K
7

Sort of. The stream is backed by a "real" operating system file descriptor, and when the process terminates the OS will clean up any open file descriptors.

Anyway, it's good practice to always close your resources when you're done, so close the streams :)

Kabob answered 5/2, 2009 at 13:58 Comment(0)
P
7

If you don't close streams, you may have problems opening them back up again. This is especially true if they're hanging off the end of sockets.

Closing a stream also makes sure that data is flushed through the stream if there is any data left to send.

Philosophy answered 5/2, 2009 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.